【问题标题】:Fetching data from has_one model从 has_one 模型中获取数据
【发布时间】:2014-05-25 22:01:20
【问题描述】:

我有这个模型:

class User < ActiveRecord::Base

  has_one :page, dependent: :destroy

end

class Page < ActiveRecord::Base
  attr_accessible :infos, :title, :user_id

  belongs_to :user

end

在页面索引视图中,当我这样做时

<%= page.user.name  %>

我可以得到值,但是在用户页面视图中,当我这样做时

<%= user.page %>

我得到了对象:#&lt;Page:0x000000045a0470&gt;

当我执行&lt;%= user.page.title %&gt; 时,我收到错误:undefined method `title' for nil:NilClass

如何以正确的方式从 has_many 模型中获取值?

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 model has-one


    【解决方案1】:

    我想通了:

    并非所有用户都有页面,所以我这样做:

    改变

    <%= user.page.title %>
    

    <%= user.page.try(:title) %>
    

    然后它修复错误。 =D

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 1970-01-01
      • 2023-04-09
      • 2012-08-14
      • 1970-01-01
      • 2017-07-02
      • 1970-01-01
      • 2016-08-11
      • 2015-03-30
      相关资源
      最近更新 更多