我正在尝试创建表单来创建事件。事件属于(类用户的)创建者,表单中包含创建者的字段。
表单在很大程度上是有效的——它正确地呈现了其他所有内容,当fields_for@event.creator部分被注释掉时,创建操作会正确地处理它。fields_for标记呈现的是event[user]标记,而不是event[creater]标记,我不知道为什么。想法?以下是相关摘录。
(在视图/事件/new.html.erb中)
<%= form_for @event do |form| %>
<%= render :partial => '/events/form', :object => form %>
<%= form.submit 'Go!' %>
<% end %>
(在events/_form.html.erb中)
...
<% if !signed_in? %>
To create your event, please provide an email address and create a password. <br />
<%= form.fields_for @event.creator do |uf| %>
<div class="email_field">
<%= uf.label :email %>
<%= uf.text_field :email, :type => "email" %>
</div>
...
<% end %>
<% end %>
(控制器/事件控制器.rb)
def new
@event = Event.new
if !signed_in?
@event.build_creator
end
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @event }
end
end
(型号/事件.rb)
belongs_to :creator, :class_name => "User"
accepts_nested_attributes_for :creator
这在很大程度上起作用,但表单元素呈现为
<div class="email_field">
<label for="event_user_email">Email</label>
<input id="event_user_email" name="event[user][email]" size="30" type="email" />
</div>
<div class="password_field">
<label for="event_user_password">Password</label>
<input id="event_user_password" name="event[user][password]" size="30" type="password" />
</div>
...
这里的问题是event_user和event[user],而不是event_creator和event[creator];当我提交表单时,我收到一个错误,即事件没有"用户"字段。
<%= form.fields_for :creator, @event.creator do |uf| %>