简体   繁体   中英

How do I access a single attribute inside and array within my database - working with Ruby on Rails

I am attempting to get the 'title' from within an array called 'itemType'. 'itemType' is an attribute inside my model 'Item'.

ie: Item { attributes: { name, id, itemType: { title, icon } }

I have been able to get what I want, but only for a single item. I can not in any way loop through the items to access the whole database at once and get the title for each individual item. Ruby yells at me with :

undefined method `[]' for nil:NilClass

So far I have::

<% i = 0 %>
<% len = Item.all.length %>
<% while i < len do %>
    <% items = Item.include_object(:itemType)[i] %>
    <div class="iso_holder">
       <%= item.attributes['itemType']['title']%>
    </div>
    <% i += 1 %>
<% end %>

Any help would be appreciated :)

UPDATE:

Item Model:

class Item < ParseResource::Base
  fields :objectId, :itemType, :user, :createdAt, :updatedAt, :ACL
  validates_presence_of :user

  belongs_to :user
end

your code seems not to use the power or ruby

This should help.

<% Item.all.each do |item| %>
    <div class="iso_holder">
       <%= item.itemType.title unless item.itemType.nil? %>
    </div>
<% end %>

My Probable guess is you are getting itemType as nil somewhere in some record

also have a short look at loops in ruby

I personally feel its not worth using ruby if you are writing the same way you code in other langs :)

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