【问题标题】:Rails Understanding Active Record AssociationRails 理解 Active Record 关联
【发布时间】:2016-02-23 09:15:55
【问题描述】:

我无法理解 Active Record 关联。我有以下

<%= feed_item.spot.inspect %>

这给了我以下输出

#<Spot id: 18, name: "XX", city: "XX", created_at: "2016-02-22 22:30:00", updated_at: "2016-02-22 22:30:00">

编辑:

我想获取地点的名称 (XX)?

<%= feed_item.spot.name %>

似乎不起作用。我该怎么办?

【问题讨论】:

标签: ruby-on-rails activerecord associations


【解决方案1】:

您收到此错误是因为 spotnil。如果您的 spot 被允许为 nil 您应该在之前测试该值。

<%= feed_item.spot.name if feed_item.spot.present? %>

如果不允许为 nil,则将存在验证器添加到您的 feed_item 模型中。

class YourModel < ActiveRecord::Base
  validates_presence_of :spot_id
end

这样您就可以确定spot 在新数据库中永远不会是nil

【讨论】:

  • 为什么我会得到这个:#如果现货是零?这正是我感到困惑的原因。当我做 spot.inspect 时,我不应该得到“nil”吗?
  • 在您的视图中将 &lt;%= p feed_name.spot %&gt; 添加到 &lt;%= feed_item.spot.name %&gt; 之前,然后查看控制台显示的内容。它应该返回nil
猜你喜欢
  • 1970-01-01
  • 2017-10-14
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多