0

私は2つのテーブルロールとユーザーを持っており、これらの2つのテーブルを、レールとhas_and_belongs_to_many関係でリンクしました。Rails5のhas_and_belongs_to_manyの関係テーブルから値を取得

私は正常にhas_and_belongs_to_many関係で作成された3番目のテーブルにデータを挿入します。

def create 
user_params[:password] = User.hash(user_params[:password]) 
@user = User.new(:first_name => user_params[:first_name], 
       :last_name=>user_params[:last_name], 
       :email => user_params[:email], 
       :contact_number=>user_params[:contact_number], 
       :password=>user_params[:password]) 

@roles = user_params[:roles]; 
for role in @roles 
    @user.roles << Role.find(role) 
end 
if @user.save 
    respond_to do |format| 
    msg = { :status => "ok", :message => "User Creation Success!" } 
    format.json { render :json => msg } 
    end 
end 
end 

今私の問題を次のコードを使用すると、私は関係テーブルから値を読み、どのように私は関係テーブルに任意の値を更新しない行う方法です。

答えて

0

あなたがそうのようなセットアップお使いの機種ユーザーの役割を考えることができます:

class User < ActiveRecord::Base 
    has_and_belongs_to_many :roles 
end 

class Role < ActiveRecord::Base 
    has_and_belongs_to_many :users 
end 

アブドあなたはその後、

User.first.roles

を言って、通常のように、関連するデータを取得することができます users_roles_tableテーブル を追加しました

および

Role.first.users

関連する問題