2017-10-16 73 views
0

我需要显示未选中的专业化。用户has_and_belongs_to_many专业化和专业化has_and_belongs_to_many用户。是否有可能显示当前用户未选择的专业化。需要显示当前用户未选择的专业化,访问HABTM join_table

class User < ApplicationRecord 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable, :doorkeeper 

    belongs_to :user_type, optional: true 

    has_many :comments, dependent: :destroy 
    has_many :lessons, foreign_key: :created_by 
    has_many :qualifications, dependent: :destroy 
    has_many :videos, dependent: :destroy 

    has_and_belongs_to_many :specializations 

    validates_uniqueness_of :email 

和专业化模式是

class Specialization < ApplicationRecord 
    has_and_belongs_to_many :users 

end 

并加入表

class JoinTableUserSpecialization < ActiveRecord::Migration[5.0] 


def change 
    create_join_table :users, :specializations do |t| 
     t.index [:user_id, :specialization_id], name: "index_users_on_specialization_id" 
     t.index [:specialization_id, :user_id], name: "index_specializations_on_user_id" 
    end 
    end 
end 

专业化控制器

def suggest 
    @specializations = Specialization.all 
    end 
+0

接受和upvote答案,如果我的解决方案为你工作 – krishnar

回答

0
def suggest 
@specializations = Specialization.where.not(id: current_user.specializations) 
end 
+0

谢谢先生。有用。非常感谢!! –

+0

嗨克里希纳尔。您会在此代码示例之前添加一两句话来解释为什么这是解决方案吗?我们倾向于拒绝仅有代码的答案,因为我们认为某种推理的呈现可能对未来的读者有用。谢谢! – halfer