开发者

Rails 3 finding object in a HABTM relationship

开发者 https://www.devze.com 2023-01-14 17:39 出处:网络
Have myself confused . . . I have a SubscriptionPlan ActiveRecord object which has an HABTM to available_to_roles.

Have myself confused . . .

I have a SubscriptionPlan ActiveRecord object which has an HABTM to available_to_roles.

In Rails 3 I'm trying to create a scope or class method on SubscriptionPlan to get appropriate subscription plans:

def self.available_subscription_plans(users_roles) #users_roles = Array of roles

#query to find all subscription plans where available_to_roles is in users_roles

end

Having a very hard time figuring开发者_如何学运维 out the most appropriate way to do this with the new syntax.

Thanks for any pointers in the right direction!


Confusion was due to a typo in the relationship definition and low text contrast. Answer for anybody coming along later:

class SubscriptionPlan < ActiveRecord::Base
  has_and_belongs_to_many :available_to_roles, :join_table => "[join_table_name]", :class_name => 'UserRole'

  scope :available_subscription_plans, lambda { |users_roles|
    joins(:available_to_roles)
    .where("user_roles.id IN ( ? ) AND CURRENT_DATE > active_from_date AND CURRENT_DATE < active_to_date", users_roles)}
end
0

精彩评论

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

关注公众号