开发者

named_scopes and all

开发者 https://www.devze.com 2023-01-20 07:44 出处:网络
I\'m on Rails 2.3.5. Inside my application a user could book one or more time slots for a specific day. I\'ve defined this named_scope in my Slot model:

I'm on Rails 2.3.5. Inside my application a user could book one or more time slots for a specific day. I've defined this named_scope in my Slot model:

  # day time slots
  named_scope :for_day, lambda { |day|
    if !day.blank?
      { :conditions => ['day_of_week = ?', day] }
    end
  }

I use that to retrieve all the "time slots" available in a day. However I have a page where I'd like to see all the booked slots (in other words, other user's slots too).

So when I call开发者_运维问答 the /slots url I would like to get every booked slot, when instead I call /user/2/slots I need only those for user 2.

I added this route map.resources :users, :has_many => :slots to my routes.rb and this code to my slots_controller.rb:

  def index
    if params[:user_id]
      @slots = User.find(params[:user_id]).slots
    else
      @slots = Slot.all
    end
  end

Please note that a user could also see another user's booked slots alone.

Now when I try to use the :for_day named scope above for the Slot.all array I get:

undefined method for_day for #<Array:0x104441f60>

I was able to fix It adding named_scope :all, :conditions => {} to the Slot model, but It's seems a weird solution to me.

Could you help me?


The default all method returns an array (as opposed to an association object, which is returned by your named_scope :all), so you can't call for_day on it.

However you can call named scopes directly on the class you defined them for, so just doing Slot.for_day(day) (without .all) will solve your problem.

0

精彩评论

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

关注公众号