nested_form, has_many: сквозной, обновление атрибута в модели соединения

#ruby-on-rails #ruby-on-rails-3.1 #nested-forms #nested-form-for

#ruby-on-rails #ruby-on-rails-3.1 #вложенные формы #вложенная форма-для

Вопрос:

Я использую плагин Райана Бейтса 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:organizations , но тогда мне неясно, как обновлять информацию, относящуюся к их членству в организации. В частности, в таблице членства есть атрибут 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",
 

Ответ №1:

Как я видел здесь в StackOverflow с другим вопросом, мне нужно вложить hm => t вот так

 = 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
 

Но с помощью плагина Райана Бейтса связь с организациями членства, насколько я могу судить, не построена, поэтому я создал новый метод, подобный этому:

      = f.link_to_add_hmt "Add an organisation", :organisation, :memberships
 

А затем я в значительной степени просто скопировал плагин Райана Бейтса дословно, добавив новый параметр, добавив 2 строки ниже

 def link_to_add_hmt(*args, amp;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}", amp;@fields[association])
    output.safe_concat('</div>')
    output
  end 
  @template.link_to(*args, amp;block)
end 
 

Ищите ссылки на «association_two». Это отлично работает!

Ответ №2:

Обновлено для последней версии nested_form

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