【问题标题】:Nested Form Update in Rails 3 sets foreign key as NULLRails 3 中的嵌套表单更新将外键设置为 NULL
【发布时间】:2011-06-21 04:40:00
【问题描述】:

我正在尝试使用 formtastic 嵌套表单更新用户记录。它的结构如下所示

User 
   Admin
   Address

当我发送表单以更新详细信息时,在更新地址或管理员记录时,user_id(外键)设置为 NULL。这是发送的数据,似乎没问题。

Parameters: {
             "utf8"=>"✓", "authenticity_token"=>"some token", 
             "user"=>{
                 "id"=>"16",
                 "first_name"=>"User", 
                 "last_name"=>"Name", 
                 "email"=>"username@gmail.com", 
                 "password"=>"[FILTERED]", 
                 "password_confirmation"=>"[FILTERED]", 
                 "address_attributes"=>{
                      "main_phone"=>"131231233", 
                      "address1"=>"Address 1 Line", 
                      "address2"=>"Address 2 Line", 
                      "city"=>"Lansing",  
                      "state"=>"Michigan", 
                      "zip"=>"48823", 
                      "user_id"=>"16"
                 }, 
                 "admin_attributes"=>{
                      "company_id"=>"2", 
                      "user_id"=>"16"
                 }, 
                 "roles_mask"=>"1", 
                 "user_id"=>"16"
                 }, 
                 "commit"=>"Update User Roles", 
                 "company_id"=>"2", 
                 "id"=>"16"
           }

用户模型

class User < ActiveRecord::Base
  has_one :address, :dependent => :destroy, :inverse_of => :user
  has_one :admin, :dependent => :destroy, :inverse_of => :user      
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :roles_mask, :terms_of_use,:id
  attr_accessible :owner_attributes, :admin_attributes, :address_attributes, :client_attributes
  accepts_nested_attributes_for :owner, :admin, :client, :address  
end

管理模式

class Admin < ActiveRecord::Base
  belongs_to :company
  belongs_to :user, :inverse_of => :admin

  attr_accessible :company_id, :user_id
end

*地址模型

class Address < ActiveRecord::Base
  belongs_to :user, :inverse_of => :address


  attr_accessible :address1, :user_id, :address2, :city, :state, :zip, :main_phone, :cell_phone
end

你能帮我解决这个问题吗?谢谢。

已更新型号详情。我删除了验证以保持简短。

【问题讨论】:

  • 请将您的用户和管理员模型源添加到您的问题中。
  • @Hck,用模型详细信息更新了问题。

标签: ruby-on-rails ruby ruby-on-rails-3 nested-forms formtastic


【解决方案1】:

试着改正

accepts_nested_attributes_for :owner, :admin, :client, :address

在您的用户模型中使用

accepts_nested_attributes_for :owner, :client
accepts_nested_attributes_for :admin, :address, :update_only => true

【讨论】:

    猜你喜欢
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    相关资源
    最近更新 更多