Установка атрибута одной модели в представлении создания другой модели - PullRequest
1 голос
/ 28 марта 2011

У меня есть модель пользователя с профилем has_one, и этот профиль принадлежит пользователю. В профиле есть столбец type для наследования одной таблицы, который является "исполнителем" или "слушателем". Я хочу, чтобы пользователь установил это при регистрации в новом представлении пользователя. Поэтому у меня есть этот код в виде:

<%= 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 %>   

и это в моей модели пользователя:

accepts_nested_attributes_for :profile

Но я получаю его ошибку:

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?

Почему это так и как я могу это исправить?

Кроме того, я очень смущен, почему в моем видеофрагменте появляется строка 3, в которой вообще не упоминается profile ...

UPDATE:

Вот вся форма:

<%= 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 %>

И вот три строки, относящиеся к профилям в пользовательской модели:

accepts_nested_attributes_for :profile
before_create :build_profile 
has_one :profile  

1 Ответ

5 голосов
/ 28 марта 2011

Вы должны отредактировать свою модель и установить все эти вещи в правильном порядке:

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