获取belongs_to字段的数据

时间:2015-02-08 19:11:26

标签: ruby-on-rails postgresql

我不知道如何制定我的问题,所以这就是我的问题。我的模型Vote有一个user_id字段。

我的Vote模型是:

class Vote < ActiveRecord::Base
   belongs_to :user
end

我的User模型是:

class User < ActiveRecord::Base
    has_many :votes
end

到目前为止,没什么特别的。

我的问题是,当我投票时,我会添加用户的信息。喜欢这个

@votes = Vote.all
[#<Vote: 
    id: 1,
    user: #<User: id: 1, name: "Foo">
 >]

到目前为止,我是手动完成的:

json = []
@votes = Vote.includes(:user)
@votes.each do |vote|
    tmp = vote.attributes
    tmp[:user] = vote.user.attribute
    json << tmp
end 

这样的事情。有没有办法自动完成?或者我是否必须手动创建字段?你有什么想法吗?

1 个答案:

答案 0 :(得分:0)

找到答案:

@votes = Vote.all
@votes.as_json(include: :user)

Rails Object to hash

相关问题