简体   繁体   English

如何返回通过Rails模型方法定义的属性数组以及数据库表中的属性?

[英]How do I return an array of attributes defined via a Rails model method, as well as the attributes in the database table?

I have a Rails model called Person which has database table columns for first_name and last_name. 我有一个名为Person的Rails模型,该模型具有first_name和last_name的数据库表列。 I've also defined a full_name method to return the combined first_name and last_name of the instance. 我还定义了full_name方法来返回实例的first_name和last_name的组合。

Is there a way to return an array, hash, or object which has first_name, last_name, as well as full_name? 有没有一种方法可以返回具有first_name,last_name和full_name的数组,哈希或对象?

Here's the code I have: 这是我的代码:

#person.rb
class Person < ActiveRecord::Base
  validates_presence_of :first_name, :last_name  

  def full_name
        self.first_name + " " + self.last_name
  end
end

Here's what I've tried in the Rails console: 这是我在Rails控制台中尝试过的方法:

ruby-1.8.7-p302 > person = Person.new({:first_name=>"Bruce", :last_name=>"Wayne"})
 => #<Person id: nil, first_name: "Bruce", :last_name: "Wayne", created_at: nil, updated_at: nil> 

ruby-1.8.7-p302 > person.save!
 => true 

ruby-1.8.7-p302 > Person.last
 => #<Person id: 1, first_name: "Bruce", :last_name: "Wayne", created_at: "2010-11-09 22:53:14", updated_at: "2010-11-09 22:53:14"> 

Is it possible to get something returned like this instead: 是否有可能像这样返回一些东西:

ruby-1.8.7-p302 > Person.last
 => #<Person id: 1, first_name: "Bruce", :last_name: "Wayne", :full_name: "Bruce Wayne", created_at: "2010-11-09 22:53:14", updated_at: "2010-11-09 22:53:14"> 

Or can it only return values from the database? 还是只能从数据库返回值?

Eventually, I'd like to be able to call Person.all to return an array of hashes which also includes full_name. 最终,我希望能够调用Person.all以返回还包含full_name的哈希数组。

Thanks in advanced! 提前致谢!

The first_name and last_name are DB attributes which are printed in the inspect method. first_namelast_name是在检查方法中打印的数据库属性。 If you want to access the full_name call full_name on the user object. 如果要访问full_name请在用户对象上调用full_name

User.last.full_name

So if you want a hash of users with full_name as key: 因此,如果要散列使用full_name作为键的用户的哈希:

@users = {}
User.all.each{|u| @users[u.full_name] = u}

Edit 1 编辑1

The User.last call returns an User object. User.last调用返回一个User对象。 What gets printed in the console depends upon how the inspect method on the object is implemented. 控制台中打印的内容取决于对象上检查方法的实现方式。 In case of ActiveRecord, database attributes are printed. 对于ActiveRecord,将打印数据库属性。

If you need the full name, you need to call the full_name method on the returned User object. 如果需要全名,则需要在返回的User对象上调用full_name方法。

I am still not clear what you are trying to do. 我仍然不清楚您要做什么。

Edit 2 编辑2

u = User.last
[u.full_name, u.age, u.phone] # array
{:full_name => u.full_name, :age => u.age, :phone => u.phone } #hash

Edit 3 编辑3

If you want to get a JSON format out of an object do the following 如果要从对象中获取JSON格式,请执行以下操作

u.to_json(:methods => [:full_name])

Refer to the to_json documentation for more details. 有关更多详细信息,请参考to_json 文档

Edit 4 编辑4

The to_json method has include and exclude options for you to select the attributes you need. to_json方法具有includeexclude选项,供您选择所需的属性。 The to_json method gives you total control over data selection. to_json方法使您可以完全控制数据选择。 Refer to the documentation link above for more details. 有关更多详细信息,请参考上面的文档链接。

u.to_json(:methods => [:full_name], :include => [:first_name, :last_name])

If you need to include additional attributes, add them to the :include array in the above example. 如果您需要包括其他属性,请在上面的示例中将它们添加到:include数组中。

Edit 5 编辑5

To use this along with respond_with do the following: 要将其与respond_with一起使用,请执行以下操作:

respond_with(@users, :methods => [:full_name], 
                     :include => [:first_name, :last_name])

After banging my head, it looks like a way to get an array of all DB attributes plus the full_name attribute is to do: 敲了敲我的头后,这似乎是一种获取所有数据库属性数组和full_name属性的方法:

person = Person.last.attributes
person["full_name"] = Person.last.full_name

In console this will return something like: 在控制台中,它将返回类似以下内容的内容:

=> {"first_name" => "Bruce", "created_at" => Tue Nov 09 22:53:14 UTC 2010, "updated_at" => Tue Nov 09 22:53:14 UTC 2010", "id" => 58, "last_name" => "Wayne", "full_name" => "Bruce Wayne"} 

You could do this for a single Person in one line with: 您可以对一行中的单个人员执行以下操作:

Person.first.instance_eval { attributes.merge("full_name" => full_name)}

Regarding your desire to Person.all and return hashes, why would you want this behavior? 关于您对Person.all和返回哈希的需求,您为什么要这种行为? By default it returns an array of Person instances, and I wouldn't recommend overriding a default rails method to return a different type than you would normally expect. 默认情况下,它返回一个Person实例数组,并且我不建议您重写默认的rails方法来返回与通常期望的类型不同的类型。 If you want this behavior, I would add a class method on Person, something like Person.all_hashes, that returns an array of hashes for each result. 如果您想要这种行为,我将在Person上添加一个类方法,类似于Person.all_hashes,该方法为每个结果返回一个哈希数组。

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

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