class User < ActiveRecord::Base
belongs_to :role, :polymorphic => true
class Admin < ActiveRecord::Base
has_one :user, :as => :role
class Dealer < ActiveRecord::Base
has_one :user, :as => :role
class Buyer < ActiveRecord::Base
has_one :user, :as => :role
def new
@dealer = Dealer.new
respond_to do |format|
format.html
format.xml { render :xml => @dealer }
end
end
def create
@dealer = Dealer.new(params[:dealer])
respond_to do |format|
if @dealer.save
flash[:notice] = 'Dealer was successfully created.'
format.html { redirect_to [:admin, @dealer] }
format.xml { render :xml => @dealer, :status => :created, :location => @dealer }
else
format.html { render :action => "new" }
format.xml { render :xml => @dealer.errors, :status => :unprocessable_entity }
end
end
end
Admin / dealersController中的ActiveRecord :: AssociationTypeMismatch #create 用户(#41048900)预计得到HashWithIndifferentAccess(#23699520)
{"authenticity_token"=>"+GkeOOxVi1Fxl7ccbV0Ctt5R6shyMlF+3UWgRow2RdI=",
"dealer"=>{"gender"=>"m",
"forename"=>"",
"surname"=>"",
"company"=>"",
"address1"=>"",
"address2"=>"",
"zipcode"=>"",
"city"=>"",
"country"=>"1",
"user"=>{"email"=>"",
"password"=>""},
"phone"=>"",
"mobile"=>"",
"fax"=>""},
"commit"=>"Submit"}
我想我的问题是Rails没有将请求哈希中的“用户”哈希转换为用户对象 - 但为什么以及如何让Rails这样做呢?
答案 0 :(得分:8)
刚刚花了几个小时,包括碰到这个帖子。最后在另一个论坛上找到: 属性setter期望以这种形式获得你的参数
{ ...,
"user_attributes" => {"email" => "", "password" => ""},
... }
不是
{ ...,
"user" => {"email" => "", "password" => ""},
... }
为了得到这个,你的观点应该是这样的:
form_for @dealer do |f|
...
f.fields_for :user, @dealer.user do |u|
...
end
...
end
这适用于Rails 3.0.3