【问题标题】:Rails 4.2 self-join model -- Create method returns errorRails 4.2 自连接模型——创建方法返回错误
【发布时间】:2015-05-19 06:27:09
【问题描述】:

我有一个简单的帐户自联接模型。一个帐户可以有一个父帐户和/或多个子帐户。

这是课程:

class Account < ActiveRecord::Base
  has_many :children, class_name: "Account", foreign_key: "parent_id"
  belongs_to :parent, class_name: "Account"
end

以及迁移:

class CreateAccounts < ActiveRecord::Migration
  def change
    create_table :accounts do |t|
      t.references :parent, index: true
      t.string :name
      t.string :category
      t.timestamps null: false
    end
  end
end

在控制器上调用 create 方法时,出现以下错误:

Account(#70188397277860) expected, got String(#70188381177720)

它引用了控制器中create方法的第一行:

def create
  @account = Account.new(account_params)

  respond_to do |format|
    if @account.save
      format.html { redirect_to @account, notice: 'Account was successfully created.' }
      format.json { render :show, status: :created, location: @account }
    else
      format.html { render :new }
      format.json { render json: @account.errors, status: :unprocessable_entity }
    end
  end
end

由于 Account 模型是自引用的,看起来 Rails 需要一个 Account 作为构造 Account 的参数。

Rails ActiveRecord 指南有一个有限的例子,我相信我已经密切关注,但我不知道我哪里出错了。

我已经尝试了各种排列外键类型以及没有运气的东西。任何指针表示赞赏。

编辑:

这里是由脚手架命令生成的表单,用于收集创建新帐户的信息。正如 cmets 中的@SteveTurczyn 所建议的那样,表单正在为父字段而不是 id 收集字符串。

<%= form_for(@account) do |f| %>
  <% if @account.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@account.errors.count, "error") %> prohibited this account from being saved\
:</h2>

      <ul>
      <% @account.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :parent %><br>
    <%= f.text_field :parent %>
  </div>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :category %><br>
    <%= f.text_field :category %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

EDIT2:

parent 字段从text_field 更改为number_field 对结果没有影响。

传递给create方法的参数是一样的:

{"utf8"=>"✓",
"authenticity_token"=>"pq0sp162cA7Bmn7uw67F7gOvUVLj/S+xcasVibqysiF68vheVkATsf4pwKgPqH5nawjc0BnIj3qoot8JyIeVmg==",
 "account"=>{"parent"=>"0",
 "name"=>"Foo",
 "category"=>"Bar"},
 "commit"=>"Create Account"}

我对这应该如何工作感到有些困惑。

【问题讨论】:

  • 查看视图很有用...看起来 account_params 正在将字符串传递给属性“parent”,这就是您遇到问题的原因。选择记录时是否选择了父级?也许您应该在表单上选择parent_id...返回 ID 可能会解决问题。
  • @SteveTurczyn 我正在使用支架命令生成的表单来创建新帐户。当我回到我的电脑时,我会发布代码。

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

您正在从表单中提交 parent 的 ID,但您的关联期望 parent 实际上是一个帐户对象,而不是一个帐户的 ID。

将表单更改为提交parent_id 而不是parent

【讨论】:

  • 当我将表单更改为提交parent_id时,Account对象创建成功,但数据库中的parent_id字段始终为null
  • 您的account_params 方法是否也允许parent_id 而不是parent
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-24
  • 1970-01-01
  • 2018-02-23
  • 2014-02-16
  • 1970-01-01
  • 1970-01-01
  • 2015-03-10
相关资源
最近更新 更多