简体   繁体   中英

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. Thanks for the help!

You have == when you need =>

:ID == thing.ID is evaluated to false, which leads to:

@others.find_by(false) which happens to return the first record every time.

Also, your naming of attributes is not standard - by rails convention they should be small letters: 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. You can used

other.try(:NAME)

other.name will give error if 'other = nil'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM