范围声明的rails语法

时间:2012-09-16 13:03:39

标签: ruby-on-rails

我正在努力使用Rails语法。我正在尝试为用户设置一对多的地址关系,但用户将始终拥有主地址。我已经设法使模型正常工作,但我似乎无法让表单正常工作。下面的表单用于“新注册”,但嵌套地址的字段不会显示。

我一直在嘲笑这个,似乎无法得到它。有人可以解释为什么在尝试注册新用户时,嵌套表单字段不会出现吗?

这是表格

 <%= form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:class => "form-horizontal"}) do |f| %>
    <small>Mandatory fields marked *</small><br><br>


    <%= f.fields_for :primary_address do |address_form| %>
    <div class="control-group">
        <%= address_form.label :first_name, :class => "control-label" %>
        <div class="controls">
          <%= address_form.text_field :first_name, :class => "input-xlarge" %>
        </div>
      </div>

    <div class="control-group">
        <%= address_form.label :last_name, :class => "control-label" %>
        <div class="controls">
          <%= address_form.text_field :last_name, :class => "input-xlarge" %>
        </div>
      </div>
    <% end %>

这是用户模型:

class Member::User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
  :recoverable, :rememberable, :trackable, :validatable


  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :addresses_attributes

  validates_presence_of :email

  # each user may have zero or many addresses
  # their primary email is also set as their login id.
  has_many :addresses

  has_one :primary_address, :class_name => "Address",  :conditions => "is_primary = true"

  accepts_nested_attributes_for :primary_address

end

1 个答案:

答案 0 :(得分:1)

尝试初始化一个新的primary_address,如下所示:

<%= f.fields_for resource.build_primary_address do |address_form| %>