ruby-on-rails - 在另一个模型的创建 View 中设置一个模型的属性

标签 ruby-on-rails ruby ruby-on-rails-3 nested-attributes

我有一个具有 has_one 个人资料的用户模型,该个人资料属于用户。配置文件有一个type 列用于单表继承,它是“artist”或“listener”。我希望用户在新用户 View 中注册时进行设置。因此,我有以下形式的代码:

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

更新:

这是完整的表格:

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

最佳答案

你应该编辑你的模型并按正确的顺序设置所有这些东西:

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

关于ruby-on-rails - 在另一个模型的创建 View 中设置一个模型的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5452621/

相关文章:

ruby-on-rails - rails 迁移: postgresql for md5 of random string as default

ruby-on-rails - rails 3 : Create seed data from development database

ruby-on-rails - 带有图像的 Rails 嵌套表单

ruby-on-rails - Railscasts #37 未定义方法 'each' 为 nil :nilclass

ruby-on-rails - rails 4 : How to test Controller Action

ruby - Twitter 登录无法正常工作

ruby-on-rails - 如何处理更新操作中的错误(使用Twitter gem)

ruby-on-rails - 评估 :dependent => :destroy

java - Groovy 异常后重试

mysql - 使用 Sequel 迁移重命名索引