我收到此错误:
ActiveRecord :: AssociationTypeMismatch(设计(#2199041060)预期,得到字符串(#2151988680))
我正在尝试创建一个事件,用户可以为事件输入一些信息,同时选择一个设计。每次我单击“创建”按钮时都会发生错误。
以下是我的模特:
class Design < ActiveRecord::Base
belongs_to :event # User creates an Event and selects only one Design
belongs_to :user # User could also create a Design
end
class Event < ActiveRecord::Base
belongs_to :user # A user can create as many events
has_one :design # User can only select one design for this event
end
这是我的事件控制器
def create
@event = Event.new(params[:event])
@user = current_user
@designs = Design.all
if @event.save
flash[:success] = "Event created"
@user.events << @event
redirect_to events_path
end
end
这是我的活动视图:
<%= form_for @event, :url => {:action => 'create', :id => @event.id } do |e| %>
<p>Enter a title for this event: <%= e.text_field :title %> </p>
<p>Select a design:</p>
<ul class = "list">
<% @designs.each do |design| %>
<li><%= e.radio_button :design, design.id %> <%= design.name %></li>
<% end %>
</ul>
<%= e.submit "Create" %>
<% end %>
答案 0 :(得分:2)
在您的视图中,将:design更改为:design_id。
答案 1 :(得分:1)
<%= e.radio_button :design, design.id %>
你实际上并没有将整个设计对象传递给你的事件模型 - 只是id,所以这实际上应该反过来使用:
<%= e.radio_button :design_id, design.id %>
编辑: 并添加到您的活动模型:
def design_id=(the_id)
return unless the_id
the_design = Design.find_by_id(the_id)
self.design = the_design if the_design
end