ruby-on-rails – 通过与其他属性关联,为has_many创建Rails表单
如何为has_many生成表单字段:通过具有其他属性的关联?
has_many:through关系有一个名为weight的附加列. 这是连接表的迁移文件: create_table :users_widgets do |t| t.integer :user_id t.integer :widget_id t.integer :weight t.timestamps end 模型看起来像这样: 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,: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 为简单起见,Widget和User只有一个名为ergo User.first.name和Widget.first.name的字段. 问题: >如何将具有相应权重的窗口小部件的下拉选项附加到用户创建/编辑表单? 快速注释..我对在用户窗体中创建新窗口小部件或在窗口小部件窗体中创建新用户不感兴趣,我只希望能够从现有对象中进行选择. 我正在运行Rails 3.1和simple_form 2.0.0dev来生成我的表单. 解决方法
我将使用
cocoon解决您的问题,我创建了一个用于处理动态嵌套表单的gem.我还有
an example project展示了不同类型关系的例子.
你的字面意思并不完全包含在内,但并不难从中衍生出来.在你的模型中你应该写: 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 然后,您需要创建一个部分视图,列出您链接的UserWidgets.将此部分放在名为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 在您的users / edit.html.haml中,您可以编写: = 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 希望这可以帮助. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- c# – “指定的网络密码不正确”X509Certificate
- objective-c – 使用SpriteKit时如何暂停声音
- jboss – 用于高性能/关键任务应用的JRuby / Tor
- ruby-on-rails – 连接到S3时获取“SSL_connect返
- Flash Media Live Encoder 使用帮助
- OpenOffice.org中的XML应用
- Reactor5.0源代码混淆器
- error C2338: You've instantiated std::ali
- postgresql – PHP PDO PGPOOL PGSQL – SQLSTAT
- actionscript-3 – 在变量的if语句中传递为true(