I have the following User model with a artist_attributes virtual attribute:
class User < ActiveRecord::Base
attr_accessor :artist_attributes
attr_accessible :artist_attributes
belongs_to :artist
accepts_nested_attributes_for :artist, update_only: true
end
Here is the artist model:
class Artist < ActiveRecord::Base
has_one :user
end
The problem is that the virtual attribute is not being set. For example, here my user controller:
class Members::UsersController < Members::BaseController
def update
current_user.artist_attributes = params[:user].delete(:artist_attributes)
p current_user.artist_attributes # => nil
# ...
end
end
And here is the form that is submitted:
<%= simple_form_for current_user, url: members_profile_path do |f| %>
<%= f.simple_fields_for :artist do |ff| %>
<%# ... %>
<% end %>
<%= f.submit "Edit profile", class: "btn btn-primary", disable_with: "Editing profile..." %>
<% end %>
Why isn’t the artist_attributes virtual attribute not being set? Is it because of the nested form?
Update
Here is the params hash after I submit the form:
Parameters: {
"utf8"=>"✓",
"authenticity_token"=>"XQI4y7x7CSjxUhdYvEv2bLEjitwCfXxeTBUU3+kYS4g=",
"user"=> {
"email"=>"youjiii@gmail.com",
"forename"=>"You",
"surname"=>"Jiii",
"password"=>"[FILTERED]",
"password_confirmation"=>"[FILTERED]",
"artist_attributes" => {
"bio"=>"NERVO is awesome!",
"phone_number"=>"",
"city"=>"",
"country"=>"Afghanistan"
}
},
"commit"=>"Edit profile"}
Try this:
Change
To
Nested attributes should be handled automatically by Rails. If you need a custom setter, define
artist_attributes=and you should be good. I believe Rails 4 will support hash values in Postgresql. Meannwhile look here for Rails 3: http://travisjeffery.com/b/2012/02/using-postgress-hstore-with-rails/Edit
According to your comment, I wouldn’t store it in a virtual attribute if the goal is simply to send it to your API.