簡體   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