【问题标题】:Get data of belongs_to field获取belongs_to字段的数据
【发布时间】:2015-02-08 19:11:26
【问题描述】:

我不知道如何提出我的问题,所以这是我的问题。我有一个模型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 

类似的东西。有什么办法可以自动完成吗?还是我必须手动创建字段?你有什么想法吗?

【问题讨论】:

  • 您可以通过调用@vote.user 访问特定投票“父”用户
  • 你知道 vote.user 返回用户吗?您是否希望自定义检查的输出?
  • 我更新了我的帖子。如果我有一个数组怎么办?如何构建对象以获取用户?
  • 您可以通过用户表中的条目访问所有用户属性,并且可以通过 vote.user 属性访问该表。也许您只是想访问该信息而不是将其写入您的投票表以防信息发生变化。

标签: ruby-on-rails postgresql


【解决方案1】:

只要找到答案:

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

Rails Object to hash

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多