【发布时间】:2016-02-21 09:34:47
【问题描述】:
我有三个模型,一个用户、一个配置文件和一个角色,我试图通过 配置文件 将多个角色附加到一个用户强>。
# user.rb
class User < ActiveRecord::Base
has_one :profile, dependent: :destroy
has_many :roles, through: :profile
has_many :interests, through: :profile
has_many :industries, through: :profile
end
# profile.rb
class Profile < ActiveRecord::Base
has_one :user, dependent: :destroy
has_many :roles
has_many :interests
has_many :industries
end
# role.rb
class Role < ActiveRecord::Base
has_many :profiles
has_many :users, :through => :profiles
has_many :users
end
我正在尝试在 edit.html.erb (simple_form_for)
中使用以下内容<%= f.association :roles,
as: :check_boxes,
label_method: :name,
value_method: :id,
label: 'Roles' %>
使用以下参数
params.require(:user).permit([:email, :first_name, :last_name, :admin, :password, role_ids: [] ])
我的编辑/更新方法:
# GET /users/1/edit
def edit
@user.build_profile if @user.profile.nil?
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
给我以下错误信息
无法修改关联“User#roles”,因为源反射 “角色”类通过 :has_many 关联到“个人资料”。
我已经研究这个问题几个小时了,但我似乎找不到错误。
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4