【问题标题】:Rails: activerecord update to new associationRails:activerecord 更新到新的关联
【发布时间】:2017-10-24 03:00:18
【问题描述】:

我有两个模型:用户和角色。一个用户可以有多个角色。

假设 user1 有 role1 和 role2。现在我希望 user1 拥有 role2 和 role3。

class User < ActiveRecord::Base

  has_and_belongs_to_many :roles

class Role < ActiveRecord::Base

  has_and_belongs_to_many :users

这是我的代码

user = User.find(1) 
newrole = Role.find(2) #get role3 

user.roles[0] = newrole 

user.roles[0].save  # does not work 

user.save # does not work 

ruby on rails 解决我的问题的正确方法是什么?

【问题讨论】:

  • user.roles.new = "newrole"user.roles.save
  • 我要更新角色1 -> 角色3,而不是添加新角色
  • 角色模型中角色的列名称是什么?
  • 我发现使用已知的 id 会更容易user.role_ids = [2, 3]

标签: ruby-on-rails activerecord associations has-many


【解决方案1】:

与其将记录从role1 更新为role3,更简单的方法是删除role1 的记录并为role2 创建新记录。

对于has_and_belongs_to_many,您只需要传递 id,rails 就会自动处理它。

示例:

对于 Rails 控制台:

-> @user = User.first
-> puts @user.role_ids
   # [1,2]

-> @user.role_ids = [2, 3]

这将通过删除role1 并为role3 创建记录来为用户分配新角色

edit.html.erb(视图)

假设您有一个User 的表单,并且有一个roles 的下拉菜单,可以多选

<%= form_for(book) do |f| %>
  <div class="field">
    <%= f.label :first_name %>
    <%= f.text_field :first_name %>
  </div>

  <div class="field">
    <%= f.label :roles %>
    <%= f.collection_select :role_ids, Role.all, :id, :name, {}, {:multiple => true} %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

users_controller.rb(控制器)

def update
  respond_to do |format|
    if @user.update(user_params)
      format.html { redirect_to @user, notice: 'User was successfully updated.' }
      format.json { render :show, status: :ok, location: @user }
    else
      format.html { render :edit }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

private

def user_params
    params.require(:user).permit(:first_name, :last_name, role_ids: [])
end

现在,当您选择role2role3 并提交表单时,Rails 将通过删除role1 的记录并为role3 创建另一个记录来处理它

【讨论】:

    【解决方案2】:
    user.roles.destroy(Role.find(1)) # assuming Role.find(1) == role1
    user.roles << Role.find(3) # assuming Role.find(3) == role3
    

    【讨论】:

      猜你喜欢
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 2014-01-16
      • 1970-01-01
      相关资源
      最近更新 更多