繁体   English   中英

从关联模型中获取价值

[英]Getting value from associated model

我的设置: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"
      }
     ]
}

您可以尝试在嵌套的include中使用:only键:

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

但是我将has_many :projects, :through => :user_projects到User中,这样您可以做得更简单:

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

另外,还有一个离题的警告提示:除非使用STI,否则不要在Rails中使用“类型”作为列名(即,项目类型是Project的ruby子类)。

-

编辑

这是一种将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}})
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

希望这可以帮助。

暂无
暂无

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

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