【问题标题】:Retrieve Values from Relationship table of has_and_belongs_to_many on Rails5从 Rails5 上 has_and_belongs_to_many 的关系表中检索值
【发布时间】:2016-12-27 11:02:43
【问题描述】:

我有两个表 Role 和 User,我将这两个表与 rails 的 has_and_belongs_to_many 关系链接起来。

我成功地将数据插入到由 has_and_belongs_to_many 关系创建的第三个表中。使用以下代码

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

现在我的问题是如何从关系表中读取值以及如何将任何值更新到关系表中。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-5


    【解决方案1】:

    假设您像这样设置模型用户角色:

    class User < ActiveRecord::Base
      has_and_belongs_to_many :roles
    end
    
    class Role < ActiveRecord::Base
      has_and_belongs_to_many :users
    end
    

    Abd 添加了users_roles_tabletable 然后,您可以像正常说法一样检索相关数据

    User.first.roles

    Role.first.users

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      相关资源
      最近更新 更多