Simple_form error - undefined `model_name 'method for ActiveRecord :: Relation: Class

I am trying to add some extra conditional logic to my editing action by passing params to where.

Whenever I use anything other than .find (params [: id], the undefined method for ActiveRecord :: Relation: Class

My code is below

Controller:

def edit @office = Office.where("id = ? AND company_id = ?", params[:id], @company.id ) end 

View:

 <%= simple_form_for @office, :url => settings_office_path, :html => { :class => "office_form" } do |f| %> <h1>Edit <%= @office.office_name %> Details</h1> <%= render :partial => 'form', :locals => { :f => f } %> <% end %> 

I inferred a class for @office, which is ActiveRecord :: Relation. If I just use

 @office = Office.find(params[:id]) 

the conclusion is Office.

I think this is a problem, but I don’t know how to fix it. Any ideas?

+7
source share
2 answers

The form expects that one record will be in the @office instance @office , the where method does not return a single record, but a relation, which can be several records, after the request.

The right way:

 @office = Office.where(:company_id => @company.id).find(params[:id]) 

Or even better if you have defined the relationship:

 @office = @company.offices.find(params[:id]) 
+16
source

I also had the same issue as I fixed it using .first .

Similar to this:

 def edit @office = Office.where("id = ? AND company_id = ?", params[:id], @company.id ).first end 
+4
source

All Articles