开发者

Adding conditions in rails include

开发者 https://www.devze.com 2023-03-25 05:53 出处:网络
going directly to my problem. render开发者_如何学C :json => projects.to_json(:only => [\'name\', \'id\'],:include => {:client => {:only => [\'name\']}, :deliverables => {:only =>

going directly to my problem.

render开发者_如何学C :json => projects.to_json(:only => ['name', 'id'],:include => {:client => {:only => ['name']}, :deliverables => {:only => ['name', 'id'], :include => {:tasks => {:only => ['name','id']} } } })

This is how my controller responds for json request. Now my problem is that it lists all the deliverables & tasks that are in given project but here I want to respond with tasks & deliverables that meets certain condition like all that are created in specific month.

Thanks is advance.


Here's what I did, in project model

has_many :uncompleted_deliverables, :class_name => 'Deliverable', :conditions => 'completed = false'

The same applies to deliverable model

has_many :uncompleted_tsks, :class_name => 'Task', :conditions => 'completed = false'

And then responded json in following way,

 format.json { render :json => projects.to_json(:only => ['name', 'id'],
                                                 :include => {:client => {:only => ['name']}, :uncompleted_deliverables => {:only => ['name', 'id'], :include => {:uncompleted_tsks => {:only => ['name','id']} } } }) }

Anyway thanks guys for your response..


Could you just include a proc? (see end of documentation here)

I guess the code could look something like that:

in you Project model:

def to_json(options={})
  tasks_json = Proc.new { |options|
    options[:builder].tasks do
      selected_tasks = tasks.select {|t| t.created_at > 30.days.ago } # or whatever your condition is
      selected_tasks.each do |t|
        options[:builder].task do
          options[:builder].tag!('id', t.id)
          options[:builder].tag!('name', t.name)
        end
      end
    end }

  options.merge!(:procs => [tasks_json])
end

Would that work for you?

0

精彩评论

暂无评论...
验证码 换一张
取 消