Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope with joins to get data in Rails 3

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.

like image 878
Jay Avatar asked May 03 '11 18:05

Jay


2 Answers

Rails 4

Question.joins(Answer.user_answers)

[ http://guides.rubyonrails.org/active_record_querying.html#joining-tables ]

like image 103
Chimed Palden Avatar answered Sep 24 '22 06:09

Chimed Palden


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
}
like image 34
McStretch Avatar answered Sep 25 '22 06:09

McStretch