HABTM relation find all records, excluding some based on association

后端 未结 2 1063
南旧
南旧 2021-01-22 20:04

I\'ve looked at some of the similar SO posts relating to this but I\'m struggling to get my head around it.

I have a habtm relation between Projects and Users. I\'m tryi

相关标签:
2条回答
  • 2021-01-22 20:30

    You can place a scope in your Project model like so:

    scope :not_belonging_to, lambda {|user| joins(:projects_users).where('projects_users.user_id <> ?', user.id) }}
    

    This assumes your join table name matches rails convention for HABTM associations

    To then get projects that a user doesn't belong to, first find your user, then pass them to the scope like so:

    @user = User.find(params[:id]) # example
    @unowned_projects = Project.not_belonging_to(@user)
    

    On reflection, that scope won't work as it will find projects that have more than one developer, if one of those is your guy.

    Instead, use the following:

    scope :not_belonging_to, lambda {|user| where('id NOT IN (?)', user.projects.empty? ? '' : user.projects) }
    
    0 讨论(0)
  • 2021-01-22 20:39

    From Matt's reply above, which was extremely helpful.

    I had trouble with this for a while. I attempted to use the following:

    scope :not_belonging_to, lambda {|developer| where('id NOT IN (?)', developer.projects.empty? ? '' : developer.projects) }
    

    But I received the following error:

    SQLite3::SQLException: only a single result allowed for a SELECT that is part of an expression:

    I found I needed to update the scope, adding .ids on the end. See below:

    scope :not_belonging_to, lambda {|developer| where('id NOT IN (?)', developer.projects.empty? ? '' : developer.projects.ids) }
    
    0 讨论(0)
提交回复
热议问题