如何将嵌套表单属性保存到数据库

时间:2010-05-10 08:10:23

标签: ruby-on-rails nested-forms nested-attributes

我真的不明白嵌套属性在Rails中是如何工作的。

我有2个模型,帐户和用户。帐户has_many用户。当新用户填写表单时,Rails报告

User(#2164802740) expected, got Array(#2148376200)

Rails不能从表单中读取嵌套属性吗?我该如何解决?如何将嵌套属性中的数据保存到数据库?

全部谢谢〜

以下是MVC:

帐户模型

class Account < ActiveRecord::Base
  has_many :users
  accepts_nested_attributes_for :users

  validates_presence_of       :company_name, :message => "companyname is required."
  validates_presence_of       :company_website, :message => "website is required."
end

用户模型

class User < ActiveRecord::Base
  belongs_to :account

  validates_presence_of         :user_name, :message => "username too short."
  validates_presence_of         :password, :message => "password too short."
end

帐户控制器

class AccountController < ApplicationController
  def new
  end

  def created
  end

  def create
    @account = Account.new(params[:account])
    if @account.save
      redirect_to :action => "created"
    else
      flash[:notice] = "error!!!"
      render :action => "new"
    end
  end
end

帐户/新视图

<h1>Account#new</h1>

<% form_for :account, :url => { :action => "create" } do |f| %>
    <% f.fields_for :users do |ff| %>
    <p>
        <%= ff.label :user_name %><br />
        <%= ff.text_field :user_name %>
    </p>
    <p>
        <%= ff.label :password %><br />
        <%= ff.password_field :password %>
    </p>
    <% end %>
    <p>
        <%= f.label :company_name %><br />
        <%= f.text_field :company_name %>
    </p>
    <p>
        <%= f.label :company_website %><br />
        <%= f.text_field :company_website %>
    </p>
<% end %>

帐户迁移

class CreateAccounts < ActiveRecord::Migration
  def self.up
    create_table :accounts do |t|
      t.string :company_name
      t.string :company_website

      t.timestamps
    end
  end

  def self.down
    drop_table :accounts
  end
end

用户迁移

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :user_name
      t.string :password
      t.integer :account_id

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end

谢谢大家。 :)

1 个答案:

答案 0 :(得分:0)

更改以下视图区域:

<% form_for :account, :url => { :action => "create" } do |f| %>

成:

<% form_for @account do |f| %>

在你的控制器内你应该有这样的东西:

def new
  @account = Account.new
  # the new empty account doesn't have any users
  # so the user fields inside your view won't appear unless you specify otherwise:
  @account.users.build
  @account.users.build
  @account.users.build
end