nested_form,has_many:through,更新连接模型的属性

我正在使用ryan bates的插件nested_form,我一直在尝试为has_many编写表单:通过关系。

我有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 => "Name of the Organization" = org.input :title, :label => "Your role" = org.input :description, :as => :text, :label => "Description of the organization", 

正如我在StackOverflow上看到的另一个问题,我需要像这样嵌套hm => t

 = f.fields_for :memberships do |mem| = mem.fields_for :organisation do |org| .row .span5.org_name = org.input :name, :label => "Name of the Organization" .span5 = mem.input :title, :label => "Title in the Organization" .row .span5 = mem.input :starting_year, :label => "Starting Year" .span5 = mem.input :ending_year, :label => "Ending Year" .row .span10 = org.text_area :description, :label => "Description of Organisation" = 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[') output end @template.link_to(*args, &block) end 

查找对“association_two”的引用。 这很棒!

已更新为最新版本的nested_form

https://gist.github.com/stuartchaney/7274894