简体   繁体   中英

ActiveRecord `has_one` association extension method

I've tried to extend has_one association with method:

has_one :subscription_plan, -> { where current: true } do
  def in newspaper
    where newspaper: newspaper
  end
end

and got an error undefined method 'in' for #<SubscriptionPlan...>

But it works with has_many :

has_many :subscription_plans, -> { where current: true } do
  def in newspaper
    where(newspaper: newspaper).take
  end
end

How to make it works with has_one on Rails 4.2.1?

By accessing has_many association you receive SubscriptionPlan::ActiveRecord_Associations_CollectionProxy but with has_one you simply receive SubscriptionPlan instance itself.

So there is nothing here to be extended.

If you would provide more information about your models I would help you with exact code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM