带有设计嵌套属性的未知属性“user_id”

时间:2013-06-03 14:04:57

标签: ruby-on-rails ruby devise

我正在使用Devise gem来验证用户身份。我有一个用户模型和一个地址模型关系,其中每个用户has_one :address和每个地址belongs_to :user。当我尝试注册新用户时,我在页面加载时遇到以下错误:unknown attribute: user_id。跟踪指向我视图中看到的行<% resource.build_address...

如果我只是从我的视图中删除该行,则会加载页面,但不会显示任何嵌套的表单字段。

在Rails控制台中,我可以创建并保存一个地址,然后将该保存的地址用作将要保存的新用户的属性。

观点如下:

<% resource.build_address unless resource.address %>
  <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>

    <%= f.email_field :email, :autofocus => true, placeholder: "Your email", class: 'input-block-level' %><br>
    <%= f.password_field :password, placeholder: "Password", class: 'input-block-level' %><br>
    <%= f.password_field :password_confirmation, placeholder: "Confirm password", class: 'input-block-level' %><br>
    <%= f.text_field :favorite_cuisine, placeholder: "Favorite cuisine", class: 'input-block-level' %><br>
    <%= f.fields_for :address do |address_form| %>
      <%= address_form.text_field :street_one, placeholder: "Street", class: 'input-block-level' %><br>
      <%= address_form.text_field :street_two, placeholder: "Street #2", class: 'input-block-level' %><br>
      <%= address_form.text_field :city, placeholder: "City", class: 'input-block-level' %><br>
      <%= address_form.text_field :state, placeholder: "State", class: 'input-block-level' %><br>
      <%= address_form.text_field :zip, placeholder: "zip", class: 'input-block-level' %><br>
    <% end %>
<% end %>

我的用户模型:

has_one :address, :dependent => :destroy
accepts_nested_attributes_for :address

# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me,
:favorite_cuisine, :username, :address

validates_presence_of :email
validates_presence_of :address

我的地址模型:

belongs_to :user
attr_accessible :city, :state, :street_one, :street_two, :zip, :user_id

validates_presence_of :city
validates_presence_of :state
validates_presence_of :street_one
validates_presence_of :zip

我在哪里错了?

2 个答案:

答案 0 :(得分:2)

rails g migration AddUserIdToAddresses

然后编辑文件,

def change
  add_column :addresses, :user_id, :integer
end

然后rake db:migrate

答案 1 :(得分:0)

尝试这样的事情:

<%= f.fields_for (resource.address || :address), ... %> 

因为表单是嵌套的,所以应该根据我的知识构建一个新的表单提交。