Coming from Rails 2 to Rails 3 I've never worked so hard to understand something (side editorial).
Anyway, In a Rails 3 app i have the following models...
User:
has_many :answers
Answer:
belongs_to :user
belongs_to :question
scope :user_answers, where (:user_id => current_user.id)
Question:
has_many :answers
scope :qs_w_user_ans, joins(:questions) & (:user_answers)
The current error i am getting is "undefined method `includes_values' for :user_answers:Symbol"
There is a Question id and a User id. Each answer has question_id and user_id.
I need the questions with a user's answers linked appropriately via the ids. Can you show me where my models are wrong?
Thank you.
Rails 4
Question.joins(Answer.user_answers)
[ http://guides.rubyonrails.org/active_record_querying.html#joining-tables ]
The &
operator (which I believe is recently deprecated) is an alias for merge
, which allows you to essentially merge scopes. :user_answers
isn't a scope, so you can't use this method.
As Dinatih pointed out, you can call joins multiple times. In this case, creating different scopes for each join won't buy you much, so his method suits your case.
More info on scopes: http://archives.edgerails.info/articles/what-s-new-in-edge-rails/2010/02/23/the-skinny-on-scopes-formerly-named-scope/index.html
Update
Sorry for my misunderstanding. :user_answers
is a scope, but you're not calling it correctly in this case. You want the following:
scope :qs_w_user_ans, joins(:questions) & Answer.user_answers
When merging scopes, you call the merged scopes like class methods.
In the article I linked, the scope :published
on Post
is merged with the scope :published
on User
:
scope :published, lambda {
joins(:posts).group("users.id") & Post.published
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With