Reputation: 5355
I am writing my first real app in Rails 4. Here are my models...
class Instructor < ActiveRecord::Base
has_many :tickets
end
class Ticket < ActiveRecord::Base
belongs_to :instructor
belongs_to :tutor
end
class Tutor < ActiveRecord::Base
has_many :tickets
end
I generally manually set my foreign key relations in my controller like so...
def create
@ticket = Ticket.new(ticket_params)
@ticket.instructor = params[:instructor_id]
@ticket.tutor = params[:tutor_id]
...
I have used this convention in the past with Rails 3...but this does not work in Rails 4. I am guessing because of strong parameters. I tried using something like...
@ticket.instructor = ticket_params[:instructor_id]
...but this does not work. No error, just nothing gets saved. Here is some console output...
Parameters: {"utf8"=>"✓", "authenticity_token"=>"afnbX2Ph2aaNj7CDnbcDI9EdA74xBBSV7oSoU4uYZ2Y=", "tutor_id"=>{"id"=>"2"}, "ticket"=>{"session_type"=>"Severe", "student"=>"John Q. Student", "student_id"=>"09098", "course_id"=>"English 111", "notes"=>""}, "instructor_id"=>{"id"=>"2"}, "commit"=>"Create Ticket"}
...as you can see the instructor and tutor ids are being send in the params. However I did a puts/inspect on ticket_params...
{"session_type"=>"Severe", "student_id"=>"09098", "student"=>"John Q. Student", "course_id"=>"English 111", "notes"=>""}
...and the instructor and tutor ids are not there. Ideas?
ticket_params method was created by default in my controller. Here it is...
def ticket_params
params.require(:ticket).permit(:tutor_id, :session_type, :student_id, :student, :instructor_id, :course_id, :notes)
end
Upvotes: 0
Views: 69
Reputation: 29599
You need to define a method called ticket_params
in the controller. Something like the following
def ticket_params
params.require(:ticket).permit(:name, :date)
end
The method above basically tells the controller that it expects a params[:ticket]
to be present and the keys passed to the model will only be :name
and :date
. Read more on the github repo
UPDATE: (after ticket_params method was added to the question)
Change
@ticket.instructor = params[:instructor_id]
@ticket.tutor = params[:tutor_id]
to
@ticket.instructor_id = params[:instructor_id][:id]
@ticket.tutor_id = params[:tutor_id][:id]
Upvotes: 1