Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

ruby - Rails forms for has_many through association with additional attributes?

How can I generate form fields for a has_many :through association that has additional attributes?

The has_many :through relationship has an additional column called weight.

Here's the migration file for the join table:

create_table :users_widgets do |t|
  t.integer :user_id
  t.integer :widget_id
  t.integer :weight

  t.timestamps
end

The models look like this:

User
  has_many :widgets, :through => :users_widgets,
           :class_name => 'Widget',
           :source => :widget
  has_many :users_widgets
  accepts_nested_attributes_for :widgets # not sure if this is necessary


Widget
  has_many :users, :through => :users_widgets,
           :class_name => 'User',
           :source => :user
  has_many :users_widgets
  accepts_nested_attributes_for :users # not sure if this is necessary


UsersWidget
  belongs_to :user
  belongs_to :widget

For the sake of simplicity, Widget and User only have one field of their own called name, ergo User.first.name and Widget.first.name

Questions:

  • How would I append a dropdown selection for Widgets with the corresponding weight to the User create/edit form?

  • How can I dynamically add additional Widget forms to Users or User forms to Widgets to easily add or remove these relationships? The nested_form_for gem seems to be the perfect solution but I haven't been able to get it working.

  • Apart from the models and the form partials, are there any changes that need to be made to my controller?


Quick note.. I'm not interested in creating new Widgets in the User form or new Users in the Widget form, I only want the ability to select from existing objects.

I'm running Rails 3.1 and simple_form 2.0.0dev for generating my forms.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

base your question. I made a simple App. source is here: https://github.com/yakjuly/nest_form_example I deployed it to heroku, you can open page: http://glowing-lightning-1954.heroku.com/users/new

answers

  1. you want user form can select widget with weight, need do more work.dropdown selection can not satisfy your requirement.

  2. I mix "nested_form" in a "bootstrap-rails" plugin, you can add the nested_fields easier

  3. in my example, you need add a action calls select, and make WidgetsController#create can responsed_with :js

the code is based simple_form, you can have a try.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...