如何将变量传递给部分?

时间:2015-08-24 10:08:20

标签: ruby-on-rails ruby

我是Ruby on rails的新手,我在Windows xp上使用Rails 4.1.9,Ruby 2.0.0

这是我的模特

class Migproject < ActiveRecord::Base
    validates :name, presence: true 
        validates :clientname, presence: true
        validates :startdate, presence: true
        #validates :enddate, presence: true
        validates :is_active, presence: true
        validates :statusid, presence: true

        has_many :projectmembers, dependent: :destroy
        accepts_nested_attributes_for :projectmembers, :allow_destroy => true
    end

    class Projectmember < ActiveRecord::Base
        validates :fk_userid, presence: true
        validates :fk_roleid, presence: true

        belongs_to :roles
        belongs_to :users
        belongs_to :migproject  
    end

这是我的观点

<%= mp.fields_for :projectmembers do |pm| %>
        <%= render "projectmember_fields", :projectmembers => pm %>
      <% end %>

这是我的部分

<tr class="fields">
  <td>Select Users :</td><td><%= projectmembers.collection_select :fk_userid, User.all, :pk_userid, :fname, {:prompt => true} %></td>
  <td>&nbsp;&nbsp;&nbsp;&nbsp;Select Role :</td><td><%= projectmembers.collection_select :fk_roleid, Role.all, :pk_roleid, :rolename, {:prompt => true} %></td>
  <td><span class="removefld"><%= projectmembers.hidden_field :_destroy %><%= link_to "Remove" %></span></td>
</tr>

但是当我跑步时我得到像这样的错误

undefined local variable or method `projectmembers' for #<#<Class:0x4e13680>:0x2ea41e0>

我在哪里弄错了?

是否有其他方法可以向表单添加动态字段?

这是我的应用程序助手

module ApplicationHelper
def link_to_add_fields(name, mp, association)
        new_object = mp.object.send(association).klass.new
        id = new_object.object_id
        fields = mp.fields_for(association, new_object, child_index: id) do |build|
            render(association.to_s.singularize + "_fields", mp: build)
        end
        link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n","")})
    end 
end

我可以从同一页面渲染一个HTML块,而不是在helper中调用partial吗?

2 个答案:

答案 0 :(得分:6)

你需要这样写:

<%= render :partial => "projectmember_fields", :locals => {:projectmembers => pm} %>

guide

的“3.4.4传递局部变量”一章中的更多信息

编辑:刚刚理解。我之前有这个。您的问题来自link_to_add_fields方法,位于以下行:

render(association.to_s.singularize + "_fields", mp: build)

render调用还需要局部变量,如下所示:

render(:partial => "#{association.to_s.singularize}_fields", :locals => {:projectmembers => build}

下次,找到一种方法来显示错误的整个回溯,并查看代码的每个调用行。

答案 1 :(得分:0)

尽量不要使用表单构建器的模型名称

<%= render "projectmember_fields", pm_form: pm %>

并在部分内部:

<%= pm_form.collection_select ..