[英]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”的数组中获取“ title”。 'itemType' is an attribute inside my model 'Item'.
“ itemType”是模型“ Item”中的一个属性。
ie: Item { attributes: { name, id, itemType: { title, icon } } 即: 项目{属性:{名称,ID,项目类型:{标题,图标}}
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 :
Ruby对我大喊:
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 我可能的猜测是您在某些记录中某处将
itemType
设为nil
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 :) 我个人认为,如果您以与其他lang相同的方式编写代码,则不值得使用ruby :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.