【发布时间】: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