[英]Ruby On Rails, code in each loop in view
I have a little problem... My View: 我有一个小问题...我的看法:
--html---
<% @things each do |thing| %>
<% other = @others.find_by(:ID == thing.ID)%>---->it runs just once. Why?
<div>
<p>thing.ID</p> ---------------> This is correct.
<p>other.NAME</p> -------------> But it isn't. It is always same (fisrt value..).
</div>
<%end%>
--html--
I like this, that the other.NAME changes too. 我喜欢这个,other.NAME也要更改。 Thanks for the help! 谢谢您的帮助!
You have ==
when you need =>
您有==
何时需要=>
:ID == thing.ID
is evaluated to false, which leads to: :ID == thing.ID
被评估为false,这导致:
@others.find_by(false)
which happens to return the first record every time. @others.find_by(false)
碰巧每次都会返回第一条记录。
Also, your naming of attributes is not standard - by rails convention they should be small letters: other.name
另外,您对属性的命名也不是标准的-按照Rails的约定,它们应该为小写字母: other.name
you can used following query to find 'other' 您可以使用以下查询来查找“其他”
other = @others.find_by_ID(thing.ID)
if record not found it will return 'nil' and not 'record not found' error. 如果找不到记录,它将返回“ nil”,而不是“找不到记录”错误。 You can used 你可以用
other.try(:NAME)
other.name will give error if 'other = nil'. 如果“ other = nil”,other.name将给出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.