How can I handle this type of multi level forms in rails
I am in rails 3.1. I have the following models
class Tool < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :tool
has_many :relationships
has_many :advantages, :through => :relationships, :source => :resource, :source_type => 'Advantage'
has_many :disadvantages, :through => :relationships, :source => :resource, :source_type => 'Disadvantage'
end
class Relationship < ActiveRecord::Base
belongs_to :comment
belongs_to :resource, :polymorphic => true
end
class Disadvantage < ActiveRecord::Base
has_many :relationships, :as => :resource
has_many :comments, :through => :relationships
end
class Advantage < ActiveRecord::Base
has_many :relationships, :as => :resource
has_many :comments, :through => :relationships
end
In short, A Tool
has many comments
. A Comment
inturn is associated with Advantages
and Disadvantages
. So in my tool/show
page, I would list out all the comments.
But if I have to add comment to the tool page, there would be a form which has a textarea for comment and two multi select list boxes
for advantages and disadvantages.
And here is the catch, if the user wanna select from existing adv/disadv, the user can select from the list box or if the user wants to a add a new adv/disadv he can type it and add it, so that it is saved thru an ajax call and the new adv/disadv 开发者_StackOverflow中文版is added to the list box. How am I supposed to do this?
What you're looking for are "nested forms" - they are really straight-forward to use.
in your Gemfile add:
gem "nested_form"
1) in your main_model, you'll include a call to accepts_nested_attributes_for :nested_model
class MainModel
accepts_nested_attributes_for :nested_model
end
2) in the view for your main_model instead of form_for() , you will call nested_form_for() at the top
= nested_form_for(@main_model) do |f|
...
Check the Rails page for that method, it has interesting options, e.g. :reject_if , :allow_destroy, ...
3) in the view for the main_model, when you want to show a sub-form for the nested model, you will do
= f.fields_for :nested_model # replace with your other model name
it will then just use the _form partial for the nested_model and embed it in the view for the main_model
works like a charm!
Check these RailsCast.com episodes, which cover Nested Forms in depth:
http://railscasts.com/episodes/196-nested-model-form-part-1
http://railscasts.com/episodes/197-nested-model-form-part-2
hope this helps
精彩评论