当前位置 : 主页 > 编程语言 > ruby >

ruby-on-rails – Ruby on Rails中的多态和形式

来源:互联网 收集:自由互联 发布时间:2021-06-23
我最近一直都很满意,但多亏了这个令人敬畏的社区,我学到了很多东西. 我之前获得了多态关联所需的所有帮助,现在我有一个关于使用多态模型处理表单的问题.例如,我有Phoneable和User,所
我最近一直都很满意,但多亏了这个令人敬畏的社区,我学到了很多东西.

我之前获得了多态关联所需的所有帮助,现在我有一个关于使用多态模型处理表单的问题.例如,我有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

现在,当我创建表单时,我感到很困惑.通常我会做以下事情:

- 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

使用多态,我会以同样的方式,但使用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

在这种情况下,这是正确的方法吗?

在我们进一步讨论之前,我确实注意到了一个问题 – 你不需要与关联的has_many方面的t.references.所以你在create_user模型中不需要它.它的作用是创建phonable_id和phoneable_type列,您只需要在多态模型中.

您正在使用fields_for方法前进正确的路径.但为了实现这一点,您需要告诉模型如何处理这些字段.您可以使用accepts_nested_attributes_for类方法执行此操作.

class User < ActiveRecord::Base
  has_many :phones, :as => :phoneable

  accepts_nested_attributes_for :phones
end

还有一件小事,你需要让fields_for指向关联的确切名称

- form_for @user do |user_form|
  - user_form.fields_for :phones do |phone|

代替

- form_for @user do |user_form|
  - user_form.fields_for :phone do |phone|

并确保你删除你的迷路%> erb标签:)

有关accepts_nested_attributes_for的更多信息:http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

我希望这有帮助!

网友评论