我正在尝试创建一个具有三个模型的 Rails 3 应用程序,具有 has_many
和 belongs_to
关系。我在尝试提交表单时遇到了 AssociationTypeMismatch
错误。特别是 Location(#70232625418240) expected, got String(#70232609906560)
我设置的模型是:
- 食物
- 地点
- 月份
现在我正在努力连接食物和位置模型。我创建了一个简单的表单 @food
,它从 @location
中提取条目作为复选框。我想通过勾选来选择不同的位置,并将它们与我的 Food 模型中的 locations
索引相关联。
我试图让复选框作为数组提交,这样我就可以将位置与食物相关联。所以我要提交位置 ID,我相信这将使我能够为每个与食物条目相关联的位置提取位置名称。
我的模型是这样设置的:
食物.rb
class Food < ActiveRecord::Base
attr_accessible :area, :description, :icon, :iconSource, :image, :locations, :months, :name, :source, :type, :month_id
has_many :locations
has_many :months
end
location.rb
class Location < ActiveRecord::Base
attr_accessible :city, :region, :regionName, :state, :title, :food_id, :month_id, :locations_id
has_many :months
belongs_to :foods
end
我设置的表单如下所示:
new.html.erb
<%= form_for @food do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_field :name, placeholder: "Name", :class => 'field-name' %>
</div>
<% for location in Location.find(:all) %>
<div>
<%= check_box_tag "food[locations_id][]", location.id %>
<%= location.title %>
</div>
<% end %>
<%= f.submit "Post" %>
<% end %>
Foods Controller 正在使用创建操作来处理表单:
foods_controller.rb
class FoodsController < ApplicationController
def index
@foods = Food.all
end
def new
@food = Food.new
@locations = Location.all
end
def create
@food = Food.new(params[:food])
if @food.save
redirect_to foods_url(@food), :notice => "Food created!"
else
render :action => "new"
end
end
end
当我只输入与 Foods 模型相关的数据时,表单提交得很好。但是当我选择其中一个位置复选框并尝试提交表单时,我得到了这个 Location(#70232625418240) expected, got String(#70232609906560)
错误。这是输出的其余部分:
app/controllers/foods_controller.rb:10:in `new'
app/controllers/foods_controller.rb:10:in `create'
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"QThXhDG8pPJcRVTTW6FXmo6MhGcoUeUspBhRtrbsbig=",
"food"=>{"name"=>"Apple",
"locations"=>["1"]},
"commit"=>"Post"}
在研究了几个小时之后,我已经尝试了所有我能找到的方法来解决这个问题。我意识到我 need to be using location_id
而不是 locations
。但在那之后,我对这里的其他解决方案一无所知。有没有人遇到过类似的问题?
最佳答案
使用 location_ids
而不是 locations_id
:
<%= check_box_tag food[location_ids], location.id -%>
另请阅读 rails 3 has_many :through Form with checkboxes 的答案.
编辑:
:location_id
到 food[location_ids]
并将此 location_id
添加到 attr_accessible
中。
关于ruby-on-rails - Rails 模型错误 AssociationTypeMismatch expected, got String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18486674/