【问题标题】:accepts_nested_attributes_for with belongs_to polymorphic deviseAccept_nested_attributes_for 和 belongs_to 多态设计
【发布时间】:2014-06-18 05:30:19
【问题描述】:

我有 3 个模型和它们的关联

class User < ActiveRecord::Base
  # devise modules here
  attr_accessible :email, :password, :password_confirmation, :remember_me, :rolable_id, :rolable_type
  belongs_to :rolable, :polymorphic => true
end

class Player < ActiveRecord::Base
  attr_accessible :age, :name, :position
  has_one :user, :as => :rolable
end

class Manager < ActiveRecord::Base
  attr_accessible :age, :name
  has_one :user, :as => :rolable
end

我从 Rails 开箱即用的方式将 accepts_nested_attributes_for :rolable 放在用户模型上,在这个 accepts_nested_attributes_for with belongs_to polymorphic 问题中,我找到了一些解决方案,但所有解决方案都不适用于我。所有解决方案,当我尝试创建用户时总是出现同样的错误

    Processing by RegistrationsController#create as HTML
    Parameters: {"utf8"=>"V", "authenticity_token"=>"WKCniJza+PS5umMWCqvxFCZaRVQMPZBT4nU2fl994cU=", "user"=>{"email"=>"john@email.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "rolable_type"=>"manager", "rolable"=>{"name"=>"john", "age"=>"24"}}, "commit"=>"Sign up"}
    Completed 500 Internal Server Error in 143.0ms

    NoMethodError (undefined method `primary_key' for ActiveSupport::HashWithIndifferentAccess:Class):
    app/controllers/registrations_controller.rb:13:in `new'
    app/controllers/registrations_controller.rb:13:in `create'

【问题讨论】:

    标签: ruby-on-rails devise ruby-on-rails-3.2


    【解决方案1】:

    我的错,我使用的是嵌套形式

    <%= f.fields_for :rolable do |rf| %>
     ....
    <% end %>
    

    改成

    <%= f.fields_for :rolable_attributes do |rf| %>
     ....
    <% end %>
    

    【讨论】:

    • 嘿!添加 _attributes 对我有用。能说出它为什么起作用吗?
    【解决方案2】:

    对于polymorphic 关联,您必须维护通用模型Roll 喜欢

    class User < ActiveRecord::Base
      # devise modules here
      attr_accessible :email, :password, :password_confirmation, :remember_me
      has_many :rolls, :as => :rolable
    end
    
    class Player < ActiveRecord::Base
      attr_accessible :age, :name, :position
      has_many :rolls, :as => :rolable
    end
    
    class Manager < ActiveRecord::Base
      attr_accessible :age, :name
      has_many :rolls, :as => :rolable
    end
    
    class Roll < ActiveRecord::Base
      attr_accessible :rolable_id, :rolable_type
      belongs_to :rolable, :polymorphic=> true
    end
    

    【讨论】:

    • 我希望这是你想要的.. 多态关联
    • 说实话,我的问题早就这样了,不过我只是想起来了,试着重新打开。我不打算为我的案例添加另一个模型,因为我正在使用我的工作流应用程序Rails Devise Polymorphic - Get Render Partial Using Ajax
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 1970-01-01
    相关资源
    最近更新 更多