Scope with joins to get data in Rails 3

后端 未结 3 1014
夕颜
夕颜 2021-02-19 19:35

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:

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-19 19:44

    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
    }
    

提交回复
热议问题