【问题标题】:Rails, using has_many through and fields_forRails,使用 has_many through 和 fields_for
【发布时间】:2011-06-07 12:20:22
【问题描述】:

让这个工作有点麻烦。

class User < ActiveRecord::Base
  has_many :events, :through => :event_users
  has_many :event_users
  accepts_nested_attributes_for :event_users, :allow_destroy => true, :reject_if => proc { |obj| obj.blank? }
end

class Event < ActiveRecord::Base
  has_many :event_users
  has_many :users, :through => :event_users
  accepts_nested_attributes_for :users, :reject_if => lambda { |a| a[:nick].blank? }, :allow_destroy => true
end

class EventUser < ActiveRecord::Base
  set_table_name :events_users
  belongs_to :event
  belongs_to :user
end

表格布局:

events_users
  user_id
  event_id
  is_participating

events
  id
  name

users
  id
  name

这是表单的代码

<%= form_for @event do |f| %>
  <%= f.fields_for :users, f.object.users do |builder| %>
    <%= builder.text_field :name, "Name" %>
    <%= f.fields_for :event_users do |builder2| %>
      <%= builder2.hidden_field :is_participating, :value => true %>
    <% end %>
  <% end %>
<% end %>

我想要完成的是在 events_users 表中设置字段 is_participating,但它不起作用!

【问题讨论】:

    标签: ruby-on-rails nested-forms has-many has-many-through fields-for


    【解决方案1】:

    我遇到了同样的问题,基本上我所做的如下:

    <%= form_for @event do |f| %>
       <%= f.fields_for :event_users, @event_user do |builder| %>
          <%= builder.hidden_field :is_participating, :value => true %>
          <%= f.fields_for :users, f.object.user do |builder2| %>
             <%= builder2.text_field :name, "Name" %>
          <% end %>
       <% end %>
    <% end %>
    

    即,我切换了嵌套对象的顺序。这要求您通过声明的连接表建立关系(您这样做)。它为我保存了三个表中的所有属性。

    但是,如果您想保留当前模型,我想知道您是否不应该对第二级嵌套表单进行与第一级相同的设置。也就是说,您的 f.fields_for :event_users 后面应该跟一个逗号和该类的一个实例。

    【讨论】:

      【解决方案2】:

      您的 events_users 表是否没有“id”字段作为主键?如果您发布了 events_users 连接表的表格布局,可能会有所帮助。

      【讨论】:

      • 您的 events_users 表需要一个名为“id”的主键字段。这就是问题所在。
      • 好吧,它并没有解决 is_participating 未设置的问题。如果我用新用户保存表单然后再次更新,它会被设置,但如果我第二次添加新用户,它不会为新用户设置它......任何想法?
      • 不应该 Accept_nested_attributes_for :event_users 在 EventUser 模型上,而不是在 User 模型上?
      猜你喜欢
      • 2018-04-23
      • 2010-12-22
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 2015-11-27
      相关资源
      最近更新 更多