Ruby on rails Rails:activerecord更新到新关联
我有两个模型:用户和角色。一个用户可以有多个角色 假设user1有role1和role2。现在我想让user1拥有role2和role3Ruby on rails Rails:activerecord更新到新关联,ruby-on-rails,activerecord,associations,has-many,Ruby On Rails,Activerecord,Associations,Has Many,我有两个模型:用户和角色。一个用户可以有多个角色 假设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 RubyonRails中解决我的问题的正确方法是什么 user.roles.des
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
class Role < ActiveRecord::Base
has_and_belongs_to_many :users
RubyonRails中解决我的问题的正确方法是什么 user.roles.destroy(Role.find(1))#假设Role.find(1)=role1
user.roles.destroy(Role.find(1)) # assuming Role.find(1) == role1
user.roles << Role.find(3) # assuming Role.find(3) == role3
user.roles与其将记录从role1
更新到role3
,更简单的方法是删除role1
的记录,并为role2
创建新的记录
因为拥有并且属于许多
,您只需要传递ID,rails就会自动处理它
示例:
对于Rails控制台:
这将通过删除role1
并为role3
edit.html.erb(视图):
假设您有一个用于用户
的表单,并有一个用于角色
的下拉列表,其中包含多个选择
<%= 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 %>
现在,当您选择role2
和role3
并提交表单时,Rails只需删除role1
的记录,然后为role3
创建另一个user.roles.new=“newrole”
和user.roles.save
我想更新role1->role3,不添加新角色角色模型中角色的列名是什么?我发现如果ID是已知的user.role\u id=[2,3]
-> @user = User.first
-> puts @user.role_ids
# [1,2]
-> @user.role_ids = [2, 3]
<%= 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 %>
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