开发者

Rails, using has_many through and fields_for

I have a little trouble getting this to work.

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

Table-layout:

events_users
  user_id
  event_id
  is_participating

events
  id
  name

users
  id
  name

This is the code for the form

<%= 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, :valu开发者_运维技巧e => true %>
    <% end %>
  <% end %>
<% end %>

What I'm trying to accomplish is to set the field is_participating in the events_users table, but it doesn't work!


I had this same problem and essentially what I did was the following:

<%= 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 %>

i.e., I switched the order of the nested objects. This requires that you have a relationship through your join table declared (which you do). It saved all the attributes across the three tables for me.

If you want to keep your current model, however, I wonder if you shouldn't have the same set up for the 2nd level nested form as the first. Namely, your f.fields_for :event_users should be followed by a comma and an instance of that class.


Does your events_users table not have an 'id' field as a primary key? Might help if you posted the table layout for your events_users join table.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜