0

I'm not shure what's the right way to do this, so I hope to get some advice of how to do this 'nice'. Let's say you have a model with multiple relations as belongs_to-statements, for example a book. A book has a author (user) and a publisher:

belongs_to :user
belongs_to :publisher

Great. The user is signed to a publisher via a has many :through

has_many :contracts
has_many :publishers, through: :contracts

Same goes for the publisher model. Both, author and publisher have many books. So far so good. Now you have a publisher-show-view in which you render the book's form-partial, 'cause you want to add a book directly from the publisher's 'show'-view.

Now, you want to submit the form and cause to the relations, you have to feed the book model with the publishers and the authors-data.

The question is now, how to do this. Merging data into the params in the book's create method seems to work good: found on stackoverflow.

I've red about creating a hidden field in the form with the author_id but didn't go after it, cause it felt dirty somehow.

What would be the 'right' way to do this? Thanks in advance...

1 Answer 1

0

You can do it using Nested models forms and Nested attributes. You have two RailsCasts on the subject: part 1 and part 2 where you can see how it works. Also the mandatory documentation on subject.

If you option for this way here are an updated method versions for the latest rails versions:

  def link_to_remove_fields(name, f)
    f.hidden_field(:_destroy) + link_to_function(name, "remove_fields(this)", :class => "icon-remove")
  end

  def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
  end

because the screencast version will not work on later versions of rails.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.