Reputation: 313
First attempt at Rails associations and I am failing to get the following code working. My goal is to have the report status initially set to record id 1. Record 1 in the status table is 'OPEN'. I will later change this to 2 so it is 'CLOSED'.
Models are set as follows;
class Report < ActiveRecord::Base
has_one :status
end
class Status < ActiveRecord::Base
belongs_to :reports
end
Report controller has the following code which I can not get working;
def create
@report = Report.new(report_params)
@report.create_status(1)
if @report.save
redirect_to @report
else
render 'new'
end
end
I know the problem is with the @report.create_status(1)
however I am not able to find any clarity on the interwebs. I am clearly not looking in the right place.
Additionally, my routes.rb is configured as below, but I am not sure if this is the most correct way;
resources :reports do
resources :comments
resource :status
end
UandI's answer correct my issues. For info, I was confused with how I had my has_one and belongs_to associations configured. I had them reversed and they should be as follows in my situation;
class Report < ActiveRecord::Base
belongs_to :status
end
class Status < ActiveRecord::Base
has_one :reports
end
Upvotes: 3
Views: 400
Reputation: 3895
Assuming that the status you want to assign is status 'OPEN' and it's column name is column_name
Replace the following line:
@report.create_status(1)
with this
@report.status = Status.find_by_column_name('OPEN')
Here in above line replace the column_name
with the status's column's name of OPEN
E.G. if your column's name is status_name then the line would become @report.status = Status.find_by_status_name('OPEN')
Upvotes: 2