我尝试从嵌套的json创建一个Object。但是我收到了一个AssociationTypeMismatch错误。
我是ruby on rails的新手并不确定,这是正确的方法。
我很感谢任何提示。
该错误出现在avatars_controller.rb中的“@ avatar.from_json(json)”行中
Avatar.rb
class Avatar < ActiveRecord::Base
has_one :user
accepts_nested_attributes_for :user
end
User.rb
class User < ActiveRecord::Base
belongs_to :avatar
end
JSON
[
{
"id": 7,
"user": {
"id": 47,
"gender": "male",
"name": "Mark",
"created_at": "2015-01-07T11:44:50.991Z",
"updated_at": "2015-01-28T14:39:03.900Z"
},
"login_counter": 5,
"created_at": "2015-01-28T14:39:03.896Z",
"updated_at": "2015-03-03T12:11:43.432Z"
}
]
avatars_controller.rb
def get_data_button
json= open("http..." ).read
@avatar = Avatar.new
@avatar.from_json(json)
respond_to do |format|
if @avatar.save
format.html { redirect_to user_url }
else
format.html { render :new }
end
end
end
def avatar_params
params.require(:avatar).permit( :login_counter, user: [:gender, :name])
end
答案 0 :(得分:0)
请尝试使用此代码。
params.require(:avatar).permit( :login_counter, user_attributes: [:gender, :name])
[
{
"id": 7,
"user_attributes": {
"id": 47,
"gender": "male",
"name": "Mark",
"created_at": "2015-01-07T11:44:50.991Z",
"updated_at": "2015-01-28T14:39:03.900Z"
},
"login_counter": 5,
"created_at": "2015-01-28T14:39:03.896Z",
"updated_at": "2015-03-03T12:11:43.432Z"
} ]