Rails 3使用嵌套属性创建,用于使用AssociationTypeMismatch失败的多态模型

时间:2013-06-18 23:48:27

标签: ruby-on-rails-3.2 rails-activerecord polymorphic-associations

我有一个与地址模型具有多态关联的用户模型

class User < ActiveRecord::Base
  attr_accessible :addresses, :billing_addresses, :shipping_addresses, :shipping_same_as_billing

  has_many :addresses, dependent: :destroy

  has_many :billing_addresses, class_name: Address,  conditions: ['type = ?', :billing]
  has_many :shipping_addresses, class_name: Address,  conditions: ['type = ?', :shipping]
  accepts_nested_attributes_for :addresses
#...
end

class Address < ActiveRecord::Base
  belongs_to :user, polymorphic: true
  validates_presence_of :line1, :city, :state, :zip
  attr_accessible :line1, :line2, :city, :state, :zip, :type
#...
end

我的表格:(有趣的部分是地址块)

  = form_tag '/subscriptions', class: 'form-horizontal', id: "new_order" do |f|
    -if current_user.andand.stripe_customer_id.blank?
      = field_set_tag("Billing Information") do
        =simple_fields_for :creditcard do |cc|
          = cc.input :card_number, hint: "test cc: 4242424242424242", :wrapper => :append do
            = cc.input_field :card_number, id: "card_number", class: "input-medium",
                      size: 20, name: ""
            %div#cc_type_holder.cc_32.add-on{style:"position:absolute;width:35px"}
              %div#cc_type.cc_32
          = cc.input :cvc, input_html: { id: "cvc", class: "input-mini",
            size: 4, name: ""}, label: "CVC", hint: "This 3 or 4-digit code is usually found on the back of your credit card"
          = cc.input :expiration, as: :date,  start_year: Date.today.year,
            end_year: Date.today.year + 10, discard_day: true,
            order: [:month, :year], input_html: { class: "input-medium", name: ""}
        = simple_fields_for "user[billing_addresses]" do |billing_address|
          = billing_address.hidden_field :type, input_html: { value: "billing"}
          = billing_address.input :line1, input_html: { class: "input-medium"}
          = billing_address.input :line2, required: false, input_html: { class: "input-medium"}
          = billing_address.input :city, input_html: { class: "input-medium"}
          = billing_address.input :state, input_html: { class: "input-medium"}
          = billing_address.input :zip, input_html: { class: "input-medium"}
    -if current_user.blank?
      = field_set_tag("User Information") do
        = simple_fields_for :user do |users_post|
          = users_post.input :email, input_html: { value: session[:email], type: "email",
            placeholder: 'user@domain.com', class: "input-medium" }
          = users_post.input :password, input_html: { class: "input-medium" }
    = field_set_tag("Shipping Information") do
      = simple_fields_for "user[shipping_addresses]" do |shipping_address|
        = shipping_address.input :shipping_same_as_billing, as: :boolean, input_html: {checked: true, id: 'shipping-same-as-billing'}
        %div#shipping-form
          = shipping_address.hidden_field :type, input_html: { value: "shipping"}
          = shipping_address.input :line1, input_html: { class: "input-medium"}
          = shipping_address.input :line2, required: false, input_html: { class: "input-medium"}
          = shipping_address.input :city, input_html: { class: "input-medium"}
          = shipping_address.input :state, input_html: { class: "input-medium"}
          = shipping_address.input :zip, input_html: { class: "input-medium"}

      #stripe_error
      .form-actions
        = submit_tag t(".subscription.submit"), class: 'btn btn-success'

当我发布表单时,我收到此错误:

  

ActiveRecord :: AssociationTypeMismatch(地址(#70101930814600))   期待,得到阵列(#70101927961780)):

我在Stack上读到另一篇提到试图改变的帖子

config.cache_classes = true

没有做任何改动,我得到同样的错误。我真的不想手动建立关联。看起来ActiveRecord可以解决这个问题,我只是遗漏了一些东西。

- 编辑以供评论

Parameters: {"utf8"=>"✓", "authenticity_token"=>"HigNtHH08ER1S6p3xMUPlreWMuHngjo5S8z74jeqsO0=", "creditcard"=>{"expiration(3i)"=>"1"}, "user"=>{"billing_addresses"=>{"type"=>"", "line1"=>"1653 Main", "line2"=>"", "city"=>"Redwood City", "state"=>"California", "zip"=>"94061"}, "email"=>"tom@tom.com", "password"=>"[FILTERED]", "shipping_addresses"=>{"shipping_same_as_billing"=>"0", "type"=>"", "line1"=>"1653 Main", "line2"=>"", "city"=>"Redwood City", "state"=>"California", "zip"=>"94061"}}, "stripeToken"=>"[FILTERED]"}

这些是我发送的参数。我现在只是在控制器中调试:

Rails.logger.debug params['user']['billing_addresses']
Rails.logger.debug params['user']['shipping_addresses']
u = User.new(params["user"])
Rails.logger.debug u

{"type"=>"", "line1"=>"1653 Main", "line2"=>"", "city"=>"Redwood City", "state"=>"California", "zip"=>"94061"}
{"shipping_same_as_billing"=>"0", "type"=>"", "line1"=>"1653 Main", "line2"=>"", "city"=>"Redwood City", "state"=>"California", "zip"=>"94061"}

我看不到数组从哪里来。除非ActiveRecord正在使用shipping_addressesbilling_addresses并将它们视为地址数组...

1 个答案:

答案 0 :(得分:0)

我认为您的模型用户需要accepts_nested_attributes_for,因此请尝试将以下内容添加到user.rb

  accepts_nested_attributes_for :addresses
  accepts_nested_attributes_for :billing_addresses
  accepts_nested_attributes_for :shipping_addresses

除此之外,你得到的错误:

  

ActiveRecord :: AssociationTypeMismatch(地址(#70101930814600)预期,得到阵列(#70101927961780))

当分配的对象被赋予不正确的类型时,通常会引发错误。所以打破这个错误。您的对象Address似乎输入错误,但得到数组。你不应该在某个地方喂食阵列。

另一个关键注意事项:多态关联通过在foriegn键中添加类型列来指定关联记录。您需要一个可以指定的列。所以一个例子就是让你拥有以下内容:

class User < ActiveRecord::Base
      attr_accessible :addresses, :billing_addresses, :shipping_addresses,   
     :shipping_same_as_billing

      #Before       
      #has_many :addresses, dependent: :destroy

      #After
      has_many :addresses, :as => user, dependent => :destroy

   end 

进一步阅读:Polymorphic Associations