How can I set up conditional associations in Rails?

Anthony To

So I have two associated models Users and Magazines. They are associated by a has_many :through relationship via Subscriptions. So this is what it looks like:

class User < ActiveRecord::Base
  has_many :subscriptions
  has_many :magazines, :through => :subscriptions
end

class Subscription < ActiveRecord::Base
  belongs_to :user
  belongs_to :magazine
end

class Magazine < ActiveRecord::Base
  has_many :subscriptions
  has_many :users, :through => :subscriptions
end    

Users have a boolean attribute called paid. I only want users where paid == true to be able to subscribe to any magazines. How can I set up a conditional association like this? Thanks in advance for the help!

SHS

For the associations, you can pass a lambda before the hash options. In this lambda you can specify conditions, ordering, etc.

class Magazine < ActiveRecord::Base
  has_many :subscriptions
  has_many :users, ->{ where(users: {paid: true}) }, through: :subscriptions
end 

For users, you could do something like this:

class User < ActiveRecord::Base
  has_many :subscriptions
  has_many :magazines, through: :subscriptions

  def magazines
    self.paid ? super : Magazine.none
  end
end

While it's neat, the above might behave unpredictably when you're joining tables e.g. User.joins(:magazines) might ignore the paid condition or crash.

A better alternative:

class User < ActiveRecord::Base
  has_many  :subscriptions
  has_many  :magazines,
            ->{ where("subscriptions.user_id IN (
                  SELECT id FROM users WHERE users.paid = 't')") },
            through: :subscriptions
end

That where in the lambda might be replaceable by a joins like so:

joins(subscriptions: :user).where(users: {paid: true})

But I think that'll join subscriptions twice - once for the lambda and once for the association. I'm not certain. If so, and if that bothers you, then:

joins("INNER JOIN users ON (users.id = subscriptions.user_id)").
where(users: {paid: true})

or:

joins("INNER JOIN users ON (
  (users.id = subscriptions.user_id) AND (users.paid = 't')
)")

Also, I think you mislabeled your Subscription model as Registration

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Flycheck and Clutter - how can I set it up?

분류에서Dev

How can I set up logging for node-mongod-native?

분류에서Dev

How can I set up Git branch for automatic backups

분류에서Dev

How can I set up a house-wide sound system?

분류에서Dev

Set up of conditional redirect in htaccess

분류에서Dev

Error in set up Rails

분류에서Dev

How can I set up a Site-to-site VPN between old and new versions of pfSense?

분류에서Dev

How do I set up a server for SSH?

분류에서Dev

How do I set up an email server?

분류에서Dev

How to specify eager loading of associations in rails model

분류에서Dev

Can I set up a remote connection to Mongo on cloud nine?

분류에서Dev

I set my AWS keys and they show up in linux terminal, but Rails 4 app can't find them. Using aws-sdk and carrierwave-aws gems

분류에서Dev

How can I handle conditional comments in a ractive mustache template?

분류에서Dev

Oracle SQL - How can I write an insert statement that is conditional and looped?

분류에서Dev

How can I use conditional constructs in a bash case statement?

분류에서Dev

RAILS 3: How can I reload a partial?

분류에서Dev

How can I multiple insert the data in rails

분류에서Dev

How do I set up a bash alias for a common working folder?

분류에서Dev

How can I set Crontab for a specific hour?

분류에서Dev

how can I set the position of the element?

분류에서Dev

How can I set 3 values in spinner

분류에서Dev

How to set up maven?

분류에서Dev

Rails activerecord associations

분류에서Dev

how can I fix time duration to fill up a form

분류에서Dev

How can I broadcast and pick up a keypress event in AngularJS?

분류에서Dev

How can I center the pop-up window on the screen?

분류에서Dev

How can I change the number of items that end up in a list

분류에서Dev

How can I back up a stored procedure in SQL Server?

분류에서Dev

How can I call a method on joined table in Rails?

Related 관련 기사

  1. 1

    Flycheck and Clutter - how can I set it up?

  2. 2

    How can I set up logging for node-mongod-native?

  3. 3

    How can I set up Git branch for automatic backups

  4. 4

    How can I set up a house-wide sound system?

  5. 5

    Set up of conditional redirect in htaccess

  6. 6

    Error in set up Rails

  7. 7

    How can I set up a Site-to-site VPN between old and new versions of pfSense?

  8. 8

    How do I set up a server for SSH?

  9. 9

    How do I set up an email server?

  10. 10

    How to specify eager loading of associations in rails model

  11. 11

    Can I set up a remote connection to Mongo on cloud nine?

  12. 12

    I set my AWS keys and they show up in linux terminal, but Rails 4 app can't find them. Using aws-sdk and carrierwave-aws gems

  13. 13

    How can I handle conditional comments in a ractive mustache template?

  14. 14

    Oracle SQL - How can I write an insert statement that is conditional and looped?

  15. 15

    How can I use conditional constructs in a bash case statement?

  16. 16

    RAILS 3: How can I reload a partial?

  17. 17

    How can I multiple insert the data in rails

  18. 18

    How do I set up a bash alias for a common working folder?

  19. 19

    How can I set Crontab for a specific hour?

  20. 20

    how can I set the position of the element?

  21. 21

    How can I set 3 values in spinner

  22. 22

    How to set up maven?

  23. 23

    Rails activerecord associations

  24. 24

    how can I fix time duration to fill up a form

  25. 25

    How can I broadcast and pick up a keypress event in AngularJS?

  26. 26

    How can I center the pop-up window on the screen?

  27. 27

    How can I change the number of items that end up in a list

  28. 28

    How can I back up a stored procedure in SQL Server?

  29. 29

    How can I call a method on joined table in Rails?

뜨겁다태그

보관