Ruby On Rails - “4:Fixnum 的未定义方法‘id’”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4950491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby On Rails - "undefined method `id' for 4:Fixnum"
提问by sepp2k
I recently decided I wanted to list all the usersin my Ruby On Rails application - since I couldn't figure out how to list them any other way, I decided to use partials.
I have the following on my administration page (just hooked up to a its own administration controller):
我最近决定要users在我的 Ruby On Rails 应用程序中列出所有- 因为我无法弄清楚如何以其他方式列出它们,所以我决定使用部分。我的管理页面上有以下内容(只是连接到它自己的管理控制器):
<%= render :partial => User.find(:all) %>
I then have a file called _user.html.erbin my users view folder. This contains the following:
然后_user.html.erb我在我的用户视图文件夹中调用了一个文件。这包含以下内容:
<ul>
<% div_for @user.object_id do %>
<li><%= link_to user.username, user.username %></li>
<% end %>
</ul>
When the application runs and I go to the administration page, I get the following error:
当应用程序运行并转到管理页面时,出现以下错误:
undefined method `id' for 4:Fixnum
4:Fixnum 的未定义方法“id”
It says it's because of this line (which is in the partial file):
它说这是因为这一行(在部分文件中):
<% div_for @user.object_id do %>
I'm unsure why this happens (and have googled for hours to try and find results and only find solutions that don't work for me). I think it's something to do with my usage of the @userinstance variable, but I'm not totally sure.
我不确定为什么会发生这种情况(并且已经用谷歌搜索了几个小时试图找到结果,但只找到对我不起作用的解决方案)。我认为这与我对@user实例变量的使用有关,但我不完全确定。
回答by sepp2k
You get that error because div_forexpects an active record object as an argument, which it calls the idmethod on. You pass in a fixnum (the result of @user.object_id), which is not an active record object and does not have an idmethod.
您会收到该错误,因为div_for需要一个活动记录对象作为参数,它会在其上调用该id方法。您传入一个 fixnum( 的结果@user.object_id),它不是活动记录对象并且没有id方法。
So pass in @userinstead of @user.object_idand it will work.
所以传入@user而不是@user.object_id它会起作用。
Also you should use userinstead of @user, rails 3 does not set instance variables for partials anymore.
此外,您应该使用user而不是@user, rails 3 不再为部分设置实例变量。
回答by Gerry
Lose the .object_id part. I seriously can't think why are you using object_id!Do you have a good reason for doing so? Anyway div_for wraps a div around an object, so leave the .object_id part!
丢失 .object_id 部分。我真的想不通你为什么要使用 object_id!你这样做有充分的理由吗?无论如何 div_for 将一个 div 包裹在一个对象周围,所以留下 .object_id 部分!
回答by Jigar Bhatt
instead of object you are using it's column or visa varsa you are using at that time you will get this kind of error.
而不是您正在使用的对象,您当时正在使用它的列或签证 varsa,您将收到此类错误。
Example
例子
I am using id instead of user = User.first object.
我使用 id 而不是 user = User.first 对象。
回答by Dhanshree
Try this, it worked for me.
试试这个,它对我有用。
@item.unit_of_measure.name
instead of
代替
@item.unit_of_measure_id.name

