我有一个office
模型,它是所有当前办事处的列表。我还有calendar
模型,它只是作为公司日历。我试图在localhost:3000/calendars/new
上显示当前所有办公室的下拉列表,以便人们可以看到活动将在何处进行。当我提交表单时,我收到如下所示的错误。我也发布了所有相关代码。提前谢谢。
Calendar.rb:
class Calendar < ActiveRecord::Base
belongs_to :office
end
Office.rb:
class Office < ActiveRecord::Base
has_many :calendars
end
calendars_controller:
def new
@calendar = Calendar.new
@offices = Office.all
end
_form.html.erb:
<div class="field">
<%= f.label :office_id, class: "general-text-label" %><br>
<%= collection_select :calendar, :office, @offices, :id, :name, {include_blank: true}, {class: "selectize"} %>
</div>
错误:
参数:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"lNP3u+Hs2FYsTBTClWuwJWiwW8HTFECzGVD4CdEOgOF5WD2eNiMNHtQuHjHpynJp7CaIDio09/mhvQg5rLhgtA==", "calendar"=>{"name"=>"Listing Agent Workshop", "description"=>"ffhfh", "date"=>"Friday Feb 17, 2017", "time"=>"4:00 PM", "office"=>"2"}, "commit"=>"Save"}
答案 0 :(得分:1)
Rails正在尝试推断哪个Office
与您的新Calendar
相关联。您的日历正在构建为:
Calendar.new({"name"=>"Listing Agent Workshop", "description"=>"ffhfh", "date"=>"Friday Feb 17, 2017", "time"=>"4:00 PM", "office"=>"2"})
Rails知道office
键是一个关联的模型,但它希望该值是Office
的实际实例,而在这里它只是一个字符串。
相反,您应该指定id并让rails查找它或者首先找到该对象,如果这是一个问题。
第一种方式(改变参数):
Calendar.new({"name"=>"Listing Agent Workshop", "description"=>"ffhfh", "date"=>"Friday Feb 17, 2017", "time"=>"4:00 PM", "office_id"=>"2"})
更好的方式:
office = Office.find(calendar_params[:office])
calendar_params[:office] = office
Calendar.new(calendar_params)