Getting value from associated model
My setup: 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. 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?
Jus开发者_JS百科t to be clear, here's the JSON output I'm looking for
{
  "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"
      }
     ]
}
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.
You could try using the :only key in a nested include:
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:
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).
-
Edit
Here's a way to add project_type to UserProject like you want
class UserProject
  belongs_to :user
  belongs_to :project
  delegate :type, :to => :project, :prefix => true
end
user.to_json(:include => {:user_projects => {:methods => :project_type}})
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论