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?
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])
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With