我建立使用設計和慘慘軌道4的應用程序。當新用戶註冊時,他們不會被賦予默認角色。管理員必須通過管理面板手動分配。這就是我遇到困難的地方。我無法弄清楚如何更新連接字段中的數據。這是迄今爲止我所擁有的。如何更新數據在Rails中加入表4
我UsersController:
class UsersController < ApplicationController
before_filter :authenticate_user!
before_action :set_user, only: [:show, :update, :destroy]
def index
authorize! :index, @user, message: 'Not authorized as an administrator.'
@users = User.all
end
def show
end
def update
authorize! :update, @user, message: 'Not authorized as an administrator.'
if @user.update_attributes(user_params)
redirect_to users_path, notice: "User updated."
else
redirect_to users_path, alert: "Unable to update user."
end
end
def destroy
authorize! :destroy, @user, message: 'Not authorized as an administrator.'
unless @user == current_user
@user.destroy
redirect_to users_path, notice: "User deleted."
else
redirect_to users_path, notice: "Can't delete yourself."
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:name, :email, :role_id, :user_id)
end
end
而且我的榜樣:
class Role < ActiveRecord::Base
has_and_belongs_to_many :users, :join_table => :users_roles
belongs_to :resource, :polymorphic => true
scopify
end
我的用戶模型:
class User < ActiveRecord::Base
rolify
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
正如你可以看到它的幾乎是標準模型中產生由Devise。
而且這裏是我使用更新的作用形式:
<div id="role-options-<%= user.id %>" class="reveal-modal medium" style="display: none;">
<%= simple_form_for user, url: user_path(user), html: {method: :put, class: 'custom' } do |f| %>
<h3>Change Role</h3>
<%= f.input :role_ids, collection: Role.all, as: :radio_buttons, label_method: lambda {|t| t.name.titleize}, label: false, item_wrapper_class: 'inline', checked: user.role_ids.first %>
<%= f.submit "Change Role", class: "small button" %>
<a class="close-reveal-modal" href="#">Close</a>
<% end %>
</div>
當我檢查表單上的新角色,並提交它,我重定向到該消息的用戶頁面「用戶更新「。但是,用戶角色尚未更新。
我還是相當新的Rails,只是無法弄清楚到底是什麼,我做錯了。如果我理解正確,我需要更新user_roles表中的數據。我無法弄清楚我做錯了什麼。
也許,你應該改變'UsersController#user_params'允許':role_ids' – taro
多少角色,一個用戶可以有? – beck03076
@taro邦上!這就是問題所在。如果您將它作爲答案提交,我會樂於選擇它作爲正確的答案。 –