简体   繁体   English

从关联模型中获取价值

[英]Getting value from associated model

My setup: Rails 2.3.10, Ruby 1.8.7 我的设置:Rails 2.3.10,Ruby 1.8.7

Here are my models 这是我的模特

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

When I return a JSON string of a user and his related user_projects records, I also want to include in the user_project record the project.project_type column. 当我返回用户及其相关的user_projects记录的JSON字符串时,我还想在user_project记录中包括project.project_type列。 Note: I don't want to also include the entire project record in the results. 注意:我不想在结果中也包含整个项目记录。 A possible solution is dup the project_type field in user_projects but I prefer not to do that if possible, is there another way to accomplish this during the find/read action? 一个可能的解决方案是在user_projects中的project_type字段中复制,但是如果可能的话,我不愿意这样做,是否有另一种方法可以在查找/读取操作期间完成此操作?

Just to be clear, here's the JSON output I'm looking for 为了清楚起见,这是我正在寻找的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"
      }
     ]
}

You could try using the :only key in a nested include: 您可以尝试在嵌套的include中使用:only键:

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

But I would add has_many :projects, :through => :user_projects to User so you can do the simpler: 但是我将has_many :projects, :through => :user_projects到User中,这样您可以做得更简单:

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

Also, an off-topic cautionary note: never use 'type' as a column name in Rails unless you are using STI (ie. the project types are ruby subclasses of Project). 另外,还有一个离题的警告提示:除非使用STI,否则不要在Rails中使用“类型”作为列名(即,项目类型是Project的ruby子类)。

- -

Edit 编辑

Here's a way to add project_type to UserProject like you want 这是一种将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

Hope this helps. 希望这可以帮助。

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

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