Rails:为什么user.attributes.keys只能用于新创建的用户,而不是我找到的(find_by)或者用.where拉动的用户?

时间:2016-04-07 15:41:25

标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord

提前感谢您的帮助。 Ruby on Rails noob在这里。

我正试图绕着ActiveRecord。具体来说,一旦将某些内容保存到数据库,我该如何从数据库中提取它并进行操作。

我有一个<div class="row"> {% for news in news_set %} <article class="col-sm-4"> <!-- add your article content here...and clean it up! You have unnecessary spaces, inconsistent use of single and double quotes, and inline styles that (probably) should be defined in an external stylesheet. --> </article> {% if forloop.counter|divisibleby:3 %} </div> <div class="row"> {% endif %} {% endfor %} </div> 表和一个User表。用户Messages消息,消息has_many用户。

在Rails控制台中,作为示例,如果我创建belongs_to并通过以下方式将其存储在变量User中:

@created_user

然后尝试运行@created_user = User.create(from_number: "1234") 我得到了正确的信息。 (只有@created_user.attributes.keys的密钥列表。)

但是,如果我通过以下方式从数据库中提取用户:

@created_user

我让用户正确拉起来。 (控制台向我显示SELECT语句及其提取的内容,并且它是正确的。)

然而,当我跑步时:

@looked_up_user = User.where(from_number: "12345")

我得到@looked_up_user.attributes.keys

为什么属性只能在新创建的db元素上访问,而不是我赋给变量的任何内容?

如果我想查看undefined method 'attributes'变量中的所有键,我该怎么做?

对不起这里的基本问题,我无法理解文档:

http://guides.rubyonrails.org/active_record_querying.html http://guides.rubyonrails.org/active_record_basics.html

1 个答案:

答案 0 :(得分:0)

User.where在检测到控制台时返回Relation,而不是模型实例 - 它看起来像是包含对象的数组。

你可以做User.where(from_number: "12345").first.attributes.keysUser.find_by_from_number("12345").attributes.keys