Help with nested forms

When I browse to artist_new_path I do not see the fields from the user
table (in this example: city). Why is this?

class User < ActiveRecord::Base
has_one :artist
end


class Artist < ActiveRecord::Base
belongs_to :user
has_many :medias

validates_presence_of :band_name

accepts_nested_attributes_for :user, :reject_if => lambda { |a|
a[:user].blank? }, :allow_destroy => true
end


/app/views/artists/new

<%= form_for(@artist) do |f| %>

  • <%= f.label :band_name %> <%= f.text_field :band_name %>
  • <% f.fields_for :user do |builder| %> <%= builder.label :city %> <%= builder.text_field :city %> <% end %>
<% end %>

Anyone?

On Oct 7, 11:37 pm, Christian F. [email protected]

class Artist < ActiveRecord::Base
belongs_to :user

accepts_nested_attributes_for :user

this is backwards, artist is nested inside users but you want artist to
accept nested attributes of users.

It only works the when you are accepting attributes for the child model
from
inside the parent.

Ok… someone suggested to use virtual attributes instead. Is this the
right way to go?

Basically a registered user can sign up as an artist.
Artist model has the following fields: id, user_id, band_name
User model has: id, name, city_id, genre_id

In the artist registration form:

<%= form_for(@artist) do |f| %>

  • <%= f.label :band_name %> <%= f.text_field :band_name %>
<li class="clearfix">
  <%= f.label :city_id %>
  <%= f.grouped_collection_select(:city_id,

Country.find(:all), :cities, :name, :id, :name, { :prompt => ‘Select a
city’ }) %>

<li class="clearfix">
  <%= f.label :genre_id %>
  <%= f.collection_select :genre_id, Genre.all, :id, :name,

{ :prompt => ‘Select a genre’ } %>

<% end %>

In my artist model, I created virtual attributes:

class Artist < ActiveRecord::Base
belongs_to :user
has_many :medias

validates_presence_of :band_name
attr_accessible :band_name, :city_id, :genre_id

Virtual attribute. Needed when user wants to register as an artist

def city_id

end

Virtual attribute. Needed when user wants to register as an artist

def genre_id

end

def after_create
# Update the user fields: city_id and genre_id
self.user.update_attributes(
:city_id => self.city_id,
:genre_id => self.genre_id
)
end
end

However, when I submit the form, I get:

ActiveRecord::UnknownAttributeError in ArtistsController#create
unknown attribute: city_id

The error occurs in the artist controller def create method. The first
line: @artist = Artist.new(params[:artist])

Am I doing this right? What is wrong?

Basically, all I am trying to do is create an artist (with band_name),
and update the user model based on what values were passed (city_id,
genre_id)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs