从关联模型中获取价值

时间:2011-01-21 23:31:14

标签: ruby-on-rails

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

当我返回用户的JSON字符串及其相关的user_projects记录时,我还想在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"
      }
     ]
}

2 个答案:

答案 0 :(得分:2)

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

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

但是我会向用户添加has_many :projects, :through => :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}})

答案 1 :(得分:2)

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

希望这有帮助。