Rails 3 : Mass-assignment with ActiveAdmin and has_one
I am developing a rails application in which I have two models User
and Client
.
User
is backed by devise and is responsible for authentication and has_one
Client
which holds the client details for a given user. This relation is always present as I ensure that a Client
model is created whenever I create a User
.
For the administration area I am using ActiveAdmin
. Now, when I try to create a User
through the administration interface I use a form like this:
form do |f|
f.inputs :username, :email, :password
f.inputs :name => "Client", :for => :client do |client|
client.inputs :name, :address, ...
end
end
The problem is that either the User
nor the Client
are saved and the page is reloaded with validation errors. I have checked rails console and there's a WARNING: Can't mass-assign protected attributes: client_attributes
message every time I try to create a User
.
I have searched over this issue and found that in order to allow for mass-assignment one had to define attr_accessible
for each of the fields allowed for the assignment. So, I had put this directive in Client
model for each of the fields mentioned above and the message keeps appearing, preventing the models to be properly saved.
Does anyone have a开发者_开发技巧 clue on this?
The problem is not in your Client
model, but in your User
model - because this is the primary model you are trying to create. All you need to do is to add client_attributes
to the list of attr_accessible
attributes in your User
model, just as the error message in the log files says, e.g.:
class User < ActiveRecord::Base
attr_accessible :client_attributes
end
I imagine you already have a list of accessible attributes in the User
class. So just add client_attributes
to the end of that list.
The changes you made to your Client
model (i.e. adding a list of attributes to attr_accessible
) is not needed for this to work. If you want, you can also go ahead and undo that.
精彩评论