Try   HackMD

最近更新:20200925

容易被誤解的j系列~

js.erb

  • 已完成:新增的post可以立即按讚
    可以讓js抓到partial檔,用inner html的方式讓原本區塊裡渲染出畫面
# posts.js.erb
$('#posts-block').html("<%= j render('items/partials/posts') %>")

Ajax

未來實作:
post計數

實現不換頁的效果
Ajax前端送資料的中介,
當function執行時,ajax經過route送到controller,把資料儲存或更新

jQuery

function createWorkspace(){
  $.ajax({
    type: "POST",
    url: '/workspaces',
    data: {
      name: $("#add-workspace-name").val()
    },
    success: function(result){
      if(result.success){
        $("#add-workspace-name").val('')
        $("#created-workspaces").append(createSidebarRow(result))
        alert("新增成功!")        
      }
      else{
        alert("新增失敗!")
      }
    }
  });
}

workspace controller

  def create
    @workspace = current_user.created_workspaces.new(name: params[:name])
    @workspace.save
    room_create
    render json: { 
      success: @workspace.save,
      id: @workspace.id,
      name: @workspace.name
    }
  end

json

成功的話,把需要的資料打包成json,送到前端做假動作
(讓使用者即時知道已經更新完成)

render json: { 
  success: @workspace.save,
  id: @workspace.id,
  name: @workspace.name
}

jbuilder

rails做的事情
前後端分離時,拿json

json.extract! message, :id, :content, :user_id, :room_id, :created_at, :updated_at
json.url message_url(message, format: :json)

eg:
一開始改寫成Vue的時候,
我們有可能會把資料塞在data-attribute

<div id="column" data-list="<%= @columns.to_json(include: :tickets)%>">

</div>

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

這些資料就是從_conlumn.json.jbuilder裡拿到的

json.extract! column, :id, :name, :kanban_id, :position, :created_at, :updated_at
json.url column_url(column, format: :json)

rails gon gem

從controller送資料去js檔

https://github.com/gazay/gon
https://rubygems.org/gems/gon/versions/6.3.2

參考

Mei的筆記
龍哥