【问题标题】:Getting value from associated model从关联模型中获取价值
【发布时间】:2011-01-21 23:31:13
【问题描述】:

我的设置:Rails 2.3.10、Ruby 1.8.7

这是我的模型

class User
 has_many :user_projects
end

class Project
 has_many :user_projects
 #has a column named "project_type"
end

class UserProject
 belongs_to :user
 belongs_to :project
 #fields: project_id, user_id
end

当我返回一个用户及其相关 user_projects 记录的 JSON 字符串时,我还想在 user_project 记录中包含 project.project_type 列。注意:我不想在结果中也包含整个项目记录。一个可能的解决方案是复制 user_projects 中的 project_type 字段,但如果可能的话,我不希望这样做,在查找/读取操作期间是否有其他方法可以完成此操作?

为了清楚起见,这是我正在寻找的 JSON 输出

{
  "user": {
    "username": "bob",
    "id": 1,
    "email": "bob@blah.com"
    "user_projects": [
      {
            "id": 15,
            "user_id": 1,
            "project_id": 10,
            "project_type": "marketing"
      }
      {
            "id": 22,
            "user_id": 1,
            "project_id": 11,
            "project_type": "sales"
      }
     ]
}

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:
    class UserProject
       belongs_to :user
       belongs_to :project
       #fields: project_id, user_id
       attr_reader :type
    
    
      def type
        self.project.type
      end
     end
    
     class MyController < AC
    
       def action
         @model = whatever
         respond_to do |format|
           format.json { render :json => @model.to_json(:methods => :type)}
         end
    
       end
     end
    

    希望这会有所帮助。

    【讨论】:

    • 谢谢,这更接近我的想法,除了我需要返回所有用户详细信息并包括 user_projects 加上 type 列作为 user_project 详细信息的一部分,对语法有任何想法吗?
    • 没关系,我想通了,这和我希望的完全一样,谢谢!
    • 最后一点,必须是 def self.type
    • 哎呀,我说得太早了,它显示的值为null,所以它不起作用
    • Pasta:attr_reader 行不应该在那里。 Bob:你不想要def self.type,那会让它成为一个类方法
    【解决方案2】:

    您可以尝试在嵌套包含中使用 :only 键:

    user.to_json(:include => {:user_projects => {:include => {:project => {:only => :type}}}})
    

    但我会将has_many :projects, :through =&gt; :user_projects 添加到用户,这样您就可以做更简单的事情:

    user.to_json(:include => {:projects => {:only => [:id, :type]}})
    

    另外,一个离题的注意事项:除非您使用 STI(即项目类型是 Project 的 ruby​​ 子类),否则切勿在 Rails 中使用“type”作为列名。

    -

    编辑

    这是一种将project_type 添加到 UserProject 的方法

    class UserProject
      belongs_to :user
      belongs_to :project
      delegate :type, :to => :project, :prefix => true
    end
    
    user.to_json(:include => {:user_projects => {:methods => :project_type}})
    

    【讨论】:

    • 关于不使用“类型”作为列的好点,我实际上没有这样做,对我来说是个坏例子。我更喜欢只在 user_project 范围内的上下文中返回 user_projects.user_id、project_id 和 project.type 列,有没有办法做到这一点?我认为我可以使用 attr_accessor 并在访问 user_project 记录但无法使其正常工作时以某种方式从项目中提取值。
    • 看我的回答,看来是你想要达到的目标
    猜你喜欢
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多