Bra*_*man 3 polymorphism ruby-on-rails
我最近一直都很满意,但多亏了这个令人敬畏的社区,我学到了很多东西.
我之前获得了多态关联所需的所有帮助,现在我有一个关于使用多态模型处理表单的问题.例如,我有Phoneable和User,所以当我创建我的表单来注册用户时,我希望能够为用户分配一些电话号码(即:cell,work,home).
class User < ActiveRecord::Base
has_many :phones, :as => :phoneable
end
class Phone < ActiveRecord::Base
belongs_to :phoneable, :polymorphic => true
end
class CreateUsers < ActiveRecord::Migration
t.column :name, :string
t.references :phoneable, :polymorphic => true
end
class CreatePhones < ActiveRecord::Migration
t.column :area_code, :integer
t.column :number, :integer
t.column :type, :string
t.references :phoneable, :polymorphic => true
end
Run Code Online (Sandbox Code Playgroud)
现在,当我创建表单时,我感到很困惑.通常我会做以下事情:
- form_for :user, :html => {:multipart => true} do |form|
%fieldset
%label{:for => "name"} Name:
= form.text_field :name
##now how do I go about adding a phone number?
##typically I'd do this:
##%label{:for => "phone"} Phone:
##= form.text_field :phone
Run Code Online (Sandbox Code Playgroud)
使用多态,我会以同样的方式,但使用fields_for?
- user_form.fields_for :phone do |phone| %>
%label{for => "area_code"} Area Code:
= phone.text_field :area_code
%label{for => "number"} Number:
= phone.text_field :number
Run Code Online (Sandbox Code Playgroud)
在这种情况下,这是正确的方法吗?
在我们走得更远之前,我确实注意到了一个问题 - 你不需要t.references与has_many协会的一方.所以你在create_user模型中不需要它.它的作用是创建phonable_id和phoneable_type列,你只需要在多态模型中.
你正沿着正确的道路前进fields_for.但为了实现这一点,您需要告诉模型如何处理这些字段.你可以用accepts_nested_attributes_forclass方法做到这一点.
class User < ActiveRecord::Base
has_many :phones, :as => :phoneable
accepts_nested_attributes_for :phones
end
Run Code Online (Sandbox Code Playgroud)
还有一件小事,你需要fields_for指出关联的确切名称
- form_for @user do |user_form|
- user_form.fields_for :phones do |phone|
Run Code Online (Sandbox Code Playgroud)
代替
- form_for @user do |user_form|
- user_form.fields_for :phone do |phone|
Run Code Online (Sandbox Code Playgroud)
并确保你删除你的迷路%>erb标签:)
更多信息accepts_nested_attributes_for:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html
我希望这有帮助!