Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to add some more conditional logic to my edit action by passing params into a where.

Whenever I use anything other than .find(params[:id], the error undefined method `model_name' 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 outputted the class for @office which is ActiveRecord::Relation. If I just use

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

the output is Office.

I think this is the problem but don't know how to fix it. Any ideas?

like image 887
Edward Ford Avatar asked Jan 04 '11 21:01

Edward Ford


2 Answers

The form expects a single record to be in the @office instance variable, the where-method doesn't return a single record but a relation, which can be multiple records, once queried.

The correct way is:

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

Or even better, if you've defined the relation:

@office = @company.offices.find(params[:id])
like image 63
iain Avatar answered Nov 08 '22 06:11

iain


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

Similar to this one :

def edit
   @office = Office.where("id = ? AND company_id = ?", params[:id], @company.id ).first
end
like image 32
Sachin Prasad Avatar answered Nov 08 '22 06:11

Sachin Prasad