Justin Meltzer
Justin Meltzer

Reputation: 13558

Setting attribute of one model in the create view of another model

I have a user model that has_one profile, and the profile belongs to the user. The profile has a type column for single table inheritance that is either "artist" or "listener". I want the user to set this upon signing up in the new User view. I therefore have this code in the form:

<%= f.fields_for :profile do |t| %>
 <div class ="field">
    <%= t.label :type, "Are you an artist or listener?" %><br />
    <%= t.radio_button :type "artist" %>
    <%= t.radio_button :type "listener" %>
  </div>
<% end %>   

and this in my user model:

accepts_nested_attributes_for :profile

But I get his error:

ArgumentError in Videos#index

Showing /rubyprograms/dreamstill/app/views/videos/_video.html.erb where line #3 raised:

No association found for name `profile'. Has it been defined yet?

Why is this, and how can I fix it?

Also I am very confused why the error brings up line 3 in my video partial, which does not mention profile at all...

UPDATE:

Here's the entire form:

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
  <div id="errorExplanation">
    <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
    <ul>
    <% @user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
  <% end %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </div>
  <div class="field">
    <%= f.label :password_confirmation, "Password Confirmation" %><br />
    <%= f.password_field :password_confirmation %>
  </div>
  <%= f.fields_for :profile do |t| %>
    <div class ="field">
      <%= t.label :type, "Are you an artist or listener?" %><br />
      <%= t.radio_button :type "artist" %>
      <%= t.radio_button :type "listener" %>
    </div>
  <% end %>     
  <div class="field">
    <%= f.label :name, "Full Name" %><br />
    <%= f.text_field :name %>
  </div>
  <div class="action">
    <%= f.submit %>
  </div>
<% end %>

And these are the three lines relevant to profiles in the user model:

accepts_nested_attributes_for :profile
before_create :build_profile 
has_one :profile  

Upvotes: 1

Views: 1819

Answers (1)

fl00r
fl00r

Reputation: 83680

you should edit your model and set all this stuff in right order:

has_one :profile  # it should be first
accepts_nested_attributes_for :profile
before_create :build_profile 

Upvotes: 5

Related Questions