简体   繁体   English

Model.where(…).first属性不是nil,而是显示nil

[英]Model.where(…).first attribute is not nil but shows nil

I'm playing with rails console: 我正在使用Rails控制台:

a = Event.where("location_id IS NULL")
  Event Load (0.7ms)  SELECT "events".* FROM "events" WHERE (start_date >= '2015-02-20' OR end_date >= '2015-02-20') AND (location_id IS NULL)
 => #<ActiveRecord::Relation [#<Event id: 58, name: "BENNY GREB CLINIC w Hard Rock Cafe Warszawa", start_date: "2015-02-21", end_date: nil, location: "Hard Rock Cafe Warsaw,ul. Złota 59,Warsaw,Poland", logo_url: "https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-...", website: "", facebook: "https://www.facebook.com/events/535924839876600", created_at: "2015-02-19 17:38:29", updated_at: "2015-02-19 17:38:29", logo_file_file_name: nil, logo_file_content_type: nil, logo_file_file_size: nil, logo_file_updated_at: nil, location_id: nil>]> 

So location: "Hard Rock Cafe Warsaw,ul. Złota 59,Warsaw,Poland" location: "Hard Rock Cafe Warsaw,ul. Złota 59,Warsaw,Poland"

But when I do: 但是当我这样做时:

2.2.0 :002 > a.first.location

I get 我懂了

 => nil 

Why? 为什么?

You have a location attribute and a location association and rails is using the association. 您具有位置属性和位置关联,并且Rails正在使用该关联。 You need to rethink your database structure so they are named differently. 您需要重新考虑数据库结构,以使它们的名称不同。

As per the first comment in the question: 根据问题的第一条评论:

You might be using an active record association: 您可能正在使用活动记录关联:

has_one :location

or 要么

belongs_to :location

Active record will give precedence to the relation over the model attribute. 活动记录将优先于模型属性的关系。

Try adding: 尝试添加:

has_one/belongs_to :location, as: 'related_location'

To the model in order to ensure location is always defining the attribute. 为了确保位置模型始终定义属性。 And you will access to the related location (using the location_id ) using the aliased method. 然后,您将使用别名方法访问相关位置(使用location_id )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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