2011-04-21 20 views
0

我試圖設置一個Rails 3應用程序來處理與Devise和CanCan的用戶角色。複選框越來越多,但並沒有把多對多的角色

我的關係如下

class User < ActiveRecord::Base 
    has_many :users_roles 
    has_many :roles, :through => :users_roles 
end 

class Role < ActiveRecord::Base 
    has_many :users_roles 
    has_many :users, :through => :users_roles 
end 

class UsersRole < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :role 
end 

其實一切工作正常。 Devise正在完美地處理認證。 CanCan基於ability.rb限制用戶行爲。

但我設置UsersRole有一個荒謬的問題。

我已經在用戶編輯頁面上定義了複選框。

<% for role in Role.all %> 
    <%= check_box_tag "user[role_ids][]", role.id, @user.roles.include?(role) %> 
    <%=h role.name.camelize %> 
<% end %> 
<%= hidden_field_tag "user[role_ids][]", "" %> 

如果我通過控制檯創建UserRole,那麼將根據用戶角色檢查這些複選框。

但我無法使用這些複選框設置或更改角色!

我一直都在用這種語言 - 各種語法,切換到HABTM和roles_mask方法,幾次重建我的模型和控制器 - 都沒有效果。

其實我的問題的標題是不完全正確 - 複選框是把

_method put 
authenticity_token XGl6s1iyXJfahdgftc3df8q1ZeehMVzs3LxiQH98jGw= 
commit Update 
user[current_password] password 
user[email] [email protected] 
user[name] User Name 
user[password] 
user[password_confirmatio...  
user[role_ids][] 1 
user[role_ids][] 4 
user[role_ids][]  
utf8 ✓ 

但是,這些值沒有在數據庫中設置。

我在做什麼錯?

回答

2

我的猜測是,你已經在你的用戶模型和role_ids沒有被列入其中(它不應該)指定attr_accesible

如果與你的控制器的update_attributes方法調用合併然後role_ids絕不會正確設置。

如果是這種情況,那麼你應該手動可以設置role_ids在您的控制器這樣的更新或保存之前:

@user.role_ids = params[:user][:role_ids] 

當然,我不能肯定這是因爲情況您沒有在用戶模型中包含控制器代碼或任何詳細信息。

編輯:

相反,如果做在控制器中的@ user.update_attributes,你可以改變它,而不是以下:

#The same as update_attributes, but without the save 
@user.attributes = params[:user] 

# Here the role_ids get assigned manually so it does not need to be in attr_accesible 
@user.role_ids = params[:user][:role_ids] if params[:user] 

# And here it gets checked if the save was successfull 
if @user.save 
    render :action => :show 
else 
    render :action => :edit 
end 
+0

你是絕對正確的!這總是你忽視的小事情。我已經指定了role_ids作爲attr_accesible和所有作品。現在試圖實現你的控制器。你會把它稱爲before_save嗎? – 2011-04-21 07:33:16

+0

太好了。提出了一些關於如何在控制器中處理它的建議 – DanneManne 2011-04-21 08:20:21

+0

我具有相同的確切代碼,但視圖不是呈現並且收到消息:未定義的方法「first」爲false:FalseClass。請讓我知道可能是什麼問題 – amj 2011-05-05 12:11:53