【问题标题】:how to save nested form attributes to database如何将嵌套表单属性保存到数据库
【发布时间】:2023-03-24 23:27:01
【问题描述】:

我不太明白嵌套属性在 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

谢谢大家。 :)

【问题讨论】:

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


    【解决方案1】:

    更改以下视图区域:

    <% 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
    

    【讨论】:

    • 但我在更改视图后收到此错误。 ---- 为 nil 调用 id,会误为 4 -- 如果你真的想要 nil 的 id,使用 object_id
    • 您是否也修改了控制器?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多