加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 通过与其他属性关联,为has_many创建Rails表单

发布时间:2020-12-16 19:15:47 所属栏目:百科 来源:网络整理
导读:如何为has_many生成表单字段:通过具有其他属性的关联? has_many:through关系有一个名为weight的附加列. 这是连接表的迁移文件: create_table :users_widgets do |t| t.integer :user_id t.integer :widget_id t.integer :weight t.timestampsend 模型看
如何为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的字段.

问题:

>如何将具有相应权重的窗口小部件的下拉选项附加到用户创建/编辑表单?
>如何向用户或用户表单动态添加其他窗口小部件表单到窗口小部件以轻松添加或删除这些关系? nested_form_for gem似乎是完美的解决方案,但我无法让它工作.
>除了模型和表格部分之外,是否需要对我的控制器进行任何更改?

快速注释..我对在用户窗体中创建新窗口小部件或在窗口小部件窗体中创建新用户不感兴趣,我只希望能够从现有对象中进行选择.

我正在运行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

希望这可以帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读