我正在尝试创建一个模型表单,该表单允许我通过<select>
标签按名称添加引用。
例如
在数据库中已经有带有ref_name = "a"
, ref_name = "b"
,的 RefModels ref_name = "c"
。
形式:
<%= form_for @model %>
<%= f.label :ref_models, "Referenced Models:" %>
<%= f.select :ref_models, ["a","b","c"], {}, {:multiple => true} %>
控制器:
def create
@model = Model.new(model_params)
params[:model][:ref_models].each do |ref|
@ref = RefModel.where("ref_name = ?", ref)
@model.ref_models << @ref
end
respond_to do |format|
...
end
end
在我的日志中,我收到此错误:
Started POST "/models" for 127.0.0.1 at 2013-06-25 16:20:48 -0300
Processing by ModelssController#create as JS
Parameters: {"utf8"=>"✓", "models"=>{..., "ref_models"=>["a", "b", "c"], ...}, "commit"=>"Create"}
Completed 500 Internal Server Error in 2ms
ActiveRecord::AssociationTypeMismatch (RefModel(#70144007274440) expected, got String(#70144005442620)):
app/controllers/models_controller.rb:52:in `create'
有什么问题?
笔记:
我更改了“model”和“ref_model”的实际模型名称以进行概括。
编辑:错误发生在这一行:
@model = Model.new(model_params)