Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_many :through, not reloaded/reset

I have three models, two of them are linked through a join model:

 # user.rb 
 has_many :user_cards
 has_many :cards, through: :user_cards


 # cards.rb
 has_many :user_cards
 has_many :users, through: user_cards

 # user_cards.rb
 belongs_to :user
 belongs_to :card

When I want to add a card to a user, I want to specify an attribute of a UserCard, that's why I create it this way:

 # example
 user.user_cards.create(card: card, paid: true)
  • Then when I do user.cards it doesn't contain my new record.
  • If I do user.user_cards it does contain my new record.

I need to call user.cards.reset (or reload). I don't like this solution because it requires another query.

Do you know how can I have reload|refresh|update user.cards without an additional query?

Thank you!


1 Answers

Use user.cards(true) or user.cards(force_reload = true).

like image 117
tillmo Avatar answered Oct 27 '25 09:10

tillmo