提交包含两个不同模型的表单时出错

时间:2017-02-08 19:23:16

标签: ruby-on-rails ruby forms model-view-controller

我有一个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>

错误:

enter image description here

参数:

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"}

1 个答案:

答案 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)
相关问题