当前位置: 动力学知识库 > 问答 > 编程问答 >

nested forms - 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, :value => 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: