问题描述
每当我使用除.find之外的任何其他内容(params [:] id],错误未定义的方法`model_name'为ActiveRecord :: Relation:Class
我的代码在
Controller:
def edit
@office = Office.where(id =?AND company_id =?, params [:id],@ company.id)
end
查看:
<%= simple_form_for @office,:url => settings_office_path,:html => {:class =>office_form } do | f |%>
< h1>编辑<%= @ office.office_name%>详情< / h1>
<%= render:partial =>'form' :locals => {:f => f}%>
<%end%>
我输出了@office的类,它是ActiveRecord :: Relation。如果我只是使用
@ office = Office.find(params [:id])
输出是Office。
我认为这是问题,但不知道如何解决它。任何想法?
表单期望一个记录位于 @office
实例变量,其中
- 方法不会返回单个记录,而是返回一个关系,一次查询就可以是多个记录。
正确的方法是:
@office = Office.where(:company_id => @或者更好,如果你有更好的选择,或者更好,如果你有更好的选择,定义关系:
@office = @ company.offices.find(params [:id])
code>
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])
这篇关于Simple_form错误 - ActiveRecord :: Relation:Class未定义的方法`model_name'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!