rails 5.1:通过ajax将变量传递给partial

时间:2017-05-14 15:11:56

标签: ruby-on-rails ajax

我是铁杆和实验的新手。在我设法完成this后,我现在正尝试执行以下操作:

点击设置名称的链接时,其描述应该在同一页面的部分内容中呈现。我设法渲染部分,但只有我在其中放入一些静态文本。由于某种原因,我无法传递@fbs变量,因此无法选择描述。我在其他类似问题上尝试了很多不同的建议,但我真的不知道应该怎么做。我使用ruby 2.4.0和rails 5.1

这是我的_settingsfb.html.erb(它是index.html.erb的一部分,包含Link_to)

<div class="container fluid">
  <div class="row">


    <!-- settings links -->
    <div class="col-md-4 ">
<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">Settings</h3>
  </div>
  <div class="panel-body">
    <% @fbs.each do |fbs| %>
<ul>
      <li>  <%= link_to fbs.name, controller: 'settingsfb', action: 'show', id: fbs.id,remote: true %></li>
        </ul><% end %>
  </div>
</div>
</div>

    <!-- setting description -->

  <div class="col-md-4">
<div class="panel panel-default">
  <div class="panel-heading">
    <h3 class="panel-title">Description</h3>
  </div>
  <div class="panel-body">
    <div id="desc">
      <!-- here goes the description partial -->
    </div>
  </div>
</div>
</div>

这里是settingsfb_controller(相关部分)

class SettingsfbController < ApplicationController
  before_action :set_setting, only: [:show, :edit, :update, :destroy]

  # GET /settings
  # GET /settings.json
  def index
    @settings = Setting.all
    @fbs = Setting.where("Sns = 1")
  end



  # GET /settings/1
  # GET /settings/1.json
  def show
       respond_to do |format|
      format.js {render layout: false}
    end
  end

show.js.erb

$("#desc").html("<%= j render 'settingsfb/show' %>");

和_show partial

<%= @fbs.name %>

这是我点击链接时获得的

 Started GET "/settingsfb/show?id=1" for 127.0.0.1 at 2017-05-14 17:08:34 +0200
    Processing by SettingsfbController#show as JS
      Parameters: {"id"=>"1"}
      Setting Load (0.3ms)  SELECT  "settings".* FROM "settings" WHERE "settings"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
      Rendering settingsfb/show.js.erb
      Rendered settingsfb/_show.html.erb (2.6ms)
      Rendered settingsfb/show.js.erb (3.8ms)
    Completed 500 Internal Server Error in 6ms (ActiveRecord: 0.3ms)



    ActionView::Template::Error (undefined method `name' for nil:NilClass):
        1: <%= @fbs.name %>

    app/views/settingsfb/_show.html.erb:1:in `_app_views_settingsfb__show_html_erb___617047289144576595_70310163068960'
    app/views/settingsfb/show.js.erb:1:in `_app_views_settingsfb_show_js_erb___3755597588635490219_70310163079560'
    app/controllers/settingsfb_controller.rb:17:in `block (2 levels) in show'
    app/controllers/settingsfb_controller.rb:16:in `show'

任何想法?

2 个答案:

答案 0 :(得分:1)

您应该在显示操作后渲染之前初始化@fbs。因此,请在show方法的开头添加@fbs = Setting.find(params[:id])

答案 1 :(得分:0)

错误表明没有@fbs变量。您从show.js.erb视图中调用settingsFbShow partial,但未传递任何变量。尝试

$("#desc").html("<%= j render 'settingsfb/show', locals: {fbs: fbs}  %>");

然后在create.js.erb

<%= fbs.name %>