我正在使用ryan bates的插件nested_form,我一直在尝试为has_many:through关系编写我的表单。
我有3个型号:
Profile
has_many :memberships
has_many :organizations, :through => :memberships
accepts_attributes_for :organizations
attr_accessible :organization_attribtues
Membership
has_many :profiles
has_many :organizations
Organization
has_many :memberships
has_many :profiles, :though => :memberships
以下表单适用于配置文件,但组织嵌套在其中。我可以通过f.fields_for:组织创建有关组织的信息,但后来我不清楚如何更新特定于组织成员身份的信息。具体来说,在成员资格表上有一个title属性(我在下面评论它,因为它会为组织抛出一个错误的未定义方法`title')。任何帮助都会非常感激!谢谢。
= f.fields_for :organisations do |org|
= org.input :name, :label => "<strong>Name of the Organization</strong>"
= org.input :title, :label => "Your role"
= org.input :description, :as => :text, :label => "Description of the organization",
答案 0 :(得分:2)
正如我在StackOverflow上看到的另一个问题,我需要嵌套hm =&gt;是这样的
= f.fields_for :memberships do |mem|
= mem.fields_for :organisation do |org|
.row
.span5.org_name
= org.input :name, :label => "<strong>Name of the Organization</strong>"
.span5
= mem.input :title, :label => "<strong>Title in the Organization</strong>"
.row
.span5
= mem.input :starting_year, :label => "<strong>Starting Year</strong>"
.span5
= mem.input :ending_year, :label => "<strong>Ending Year</strong>"
.row
.span10
= org.text_area :description, :label => "<strong>Description of Organisation</strong>"
= mem.link_to_remove "Remove this oranisation"
= f.link_to_add "Add an organisation", :memberships
对于Ryan Bates的插件,与会员组织的关联并不是我所知道的,所以我创建了一个这样的新方法:
= f.link_to_add_hmt "Add an organisation", :organisation, :memberships
然后我几乎只是简单地复制了Ryan Bates的插件,添加了一个新的参数,在下面添加了2行
def link_to_add_hmt(*args, &block)
options = args.extract_options!.symbolize_keys
association = args.pop
association_two = args.pop
options[:class] = [options[:class], "add_nested_fields"].compact.join(" ")
options["data-association"] = association
args << (options.delete(:href) || "javascript:void(0)")
args << options
@fields ||= {}
@template.after_nested_form(association) do
model_object = object.class.reflect_on_association(association).klass.new
model_object.send(:"build_#{association_two}")
output = %Q[<div id="#{association}_fields_blueprint" style="display: none">].html_safe
output << fields_for(association, model_object, :child_index => "new_#{association}", &@fields[association])
output.safe_concat('</div>')
output
end
@template.link_to(*args, &block)
end
查找对“association_two”的引用。这很棒!
答案 1 :(得分:1)
更新了最新版本的nested_form