我有一个课程模型,并且与类别有很多关系,我在我的表单上使用多选来获取一个对象数组,一个课程也可以有一个合作伙伴,用户可以从一个选择单选,但当我想保存到数据库时,我调用params然后我得到一个字符串而不是一个对象。我不确定如何解决这个问题
<%= form_for @course do |f| %>
<section class="new_course">
<div class="row collapse">
<div class="medium-5 small-centered column">
<%= f.label :course_title, :class=>"custom-prefix-class" %>
<%= f.text_field :title, :autofocus => true, :class=>"custom-input-class" %>
</div>
</div>
<div class="row collapse">
<div class="medium-5 small-centered column">
<%= f.label :start_date, :class=>"custom-prefix-class" %>
<%= f.text_field :start_date, :class=>"custom-input-class" %>
</div>
</div>
<div class="row">
<div class="medium-5 column with_chosen">
<%= f.collection_select :categories,
Category.all ,:id,:name,
{ include_blank: true},
{ class: 'chosen-select', :multiple=>true, :data => { :placeholder => ' ' }}
%>
</div>
</div>
<div class="row">
<div class="medium-5 column">
<%= f.collection_select :partner,
Partner.all.collect, :id,:name ,
{ include_blank: true },
{ class: 'chosen-select', :multiple=>false, :data => { :placeholder => ' Brand Partner' }}
%>
</div>
</div>
在我的控制器中
def create
@course = Course.new(course_params)
end
if @course.save
render :action=>'new'
end
end
private
def course_params
params.require(:course).permit(:title, :start_date,:duration,:partner,:categories => [])
end
// rails server output
Started POST "/courses" for 127.0.0.1 at 2014-02-07 16:45:28 +0200
Processing by CoursesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"sKhAF2X6VOXTxZC9Pt51RFQfZSKdzXVWji6x4uwg+rI=", "course"=>{"title"=>"Marketing ", "start_date"=>"14-02-2014", "categories"=>["", "1", "2"], "partner"=>"1", "duration"=>"2-weeks"}, "commit"=>"Add new course"}
Completed 500 Internal Server Error in 3ms
ActiveRecord::AssociationTypeMismatch (Partner(#70274068591140) expected, got String(#70274066607160)):
app/controllers/courses_controller.rb:24:in `create'
答案 0 :(得分:0)
试试这个: -
似乎合作伙伴是一个模特,而课程也是合作伙伴,所以你 必须分配伙伴类对象而不是id作为字符串 实际上你可以看到上面的值
params[:course][:partner]
=> "1"
如果您尝试执行@ course.partner之类的操作,现在是一个字符串 ='1'它将引发如上所述的错误,因为在左侧,我们有分手关联,右边和边是字符串。
就这样做
def course_params
params.require(:course).permit(:title, :start_date,:duration,:partner,:categories => [])
if params[:course][:partner].present?
params[:course][:partner] = Partner.find params[:course][:partner]
end
end