I have an office
model which is a list of all the current offices. I also have a calendar
model which will just act as a company calendar. I am trying to get a dropdown of all the current offices to display on the localhost:3000/calendars/new
so people can see where the event will be taking place. When I go to submit the form, I get the error shown below. I have posted all relevant code as well. Thanks in advance.
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>
Error:
Parameters:
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"}
Rails is trying to infer which Office
to associate with your new Calendar
. Your calendar is being built as:
Calendar.new({"name"=>"Listing Agent Workshop", "description"=>"ffhfh", "date"=>"Friday Feb 17, 2017", "time"=>"4:00 PM", "office"=>"2"})
Rails knows the office
key is an associated model but it expect the value to be an actual instance of an Office
, instead here it's just a string.
Instead, you should either specify the id and let rails look it up or find the object first if that is a concern.
First way (change the params):
Calendar.new({"name"=>"Listing Agent Workshop", "description"=>"ffhfh", "date"=>"Friday Feb 17, 2017", "time"=>"4:00 PM", "office_id"=>"2"})
Better way:
office = Office.find(calendar_params[:office])
calendar_params[:office] = office
Calendar.new(calendar_params)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.