I try to create an Object from nested json. But I get a AssociationTypeMismatch error.
I am new to ruby on rails and not sure, it is the right way to do this.
I am thankful for any tips.
The error appears in this line "@avatar.from_json(json)" in the avatars_controller.rb
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