我试图让它工作,但它没有!
我有
class User < ActiveRecord::Base
has_many :events, :through => :event_users
has_many :event_users
accepts_nested_attributes_for :event_users
end
class Event < ActiveRecord::Base
has_many :event_users
has_many :users, :through => :event_users
accepts_nested_attributes_for :users
end
class EventUser < ActiveRecord::Base
set_table_name :events_users
belongs_to :event
belongs_to :user
accepts_nested_attributes_for :events
accepts_nested_attributes_for :users
end
还有表格布局
event_users
user_id
event_id
user_type
events
id
name
users
id
name
这是我的表格
<%= semantic_form_for @event do |f| %>
<%= f.semantic_fields_for :users, f.object.users do |f1| %>
<%= f1.text_field :name, "Name" %>
<%= f1.semantic_fields_for :event_users do |f2| %>
<%= f2.hidden_field :user_type, :value => 'participating' %>
<% end %>
<% end %>
<%= link_to_add_association 'add task', f, :users %>
<% end %>
问题是,如果我以这种方式创建一个新用户,它不会设置 user_type 的值(但它会创建一个用户和一个带有 user_id 和 event_id 的 event_users)。如果我在创建用户并提交后返回编辑表单,则 user_type 的值在 events_users 中设置。(我也试过没有formtastic)有什么建议吗?谢谢!
- - 编辑 - -
我也尝试在用户之前拥有 event_users
<%= semantic_form_for @event do |f| %>
<%= f.semantic_fields_for :event_users do |f1| %>
<%= f1.hidden_field :user_type, :value => 'participating' %>
<%= f1.semantic_fields_for :users do |f2| %>
<%= f2.text_field :name, "Name" %>
<% end %>
<% end %>
<%= link_to_add_association 'add task', f, :event_users %>
<% end %>
但它只会给我一个错误:
用户(#2366531740) 预期,得到 ActiveSupport::HashWithIndifferentAccess(#2164210940)
- 编辑 -
link_to_association 是一种 formtastic-cocoon 方法(https://github.com/nathanvda/formtastic-cocoon),但我尝试过其他方法但结果相同
- -编辑 - -
def create
@event = Event.new(params[:event])
respond_to do |format|
if @event.save
format.html { redirect_to(@event, :notice => 'Event was successfully created.') }
format.xml { render :xml => @event, :status => :created, :location => @event }
else
format.html { render :action => "new" }
format.xml { render :xml => @event.errors, :status => :unprocessable_entity }
end
end
end