How can I generate form fields for a has_many :through association that has additional attributes?
The has_many :through relationship has a
I will be solving your problem using cocoon, a gem I created to handle dynamically nested forms. I also have an example project to show examples of different types of relationships.
Yours is not literally included, but is not that hard to derive from it. In your model you should write:
class User
has_many :users_widgets
has_many :widgets, :through -> :user_widgets
accepts_nested_attributes_for :user_widgets, :reject_if => :all_blank, :allow_destroy => true
#...
end
Then you need to create a partial view which will list your linked UserWidgets. Place this partial in a file called users/_user_widget_fields.html.haml:
.nested-fields
= f.association :widget, :collection => Widget.all, :prompt => 'Choose an existing widget'
= f.input :weight, :hint => 'The weight will determine the order of the widgets'
= link_to_remove_association "remove tag", f
In your users/edit.html.haml you can then write:
= simple_form_for @user do |f|
= f.input :name
= f.simple_fields_for :user_widgets do |user_widget|
= render 'user_widget_fields', :f => user_widget
.links
= link_to_add_association 'add widget', f, :user_widgets
Hope this helps.