【发布时间】:2016-07-25 06:22:16
【问题描述】:
我有一个叫做“BillApp”的练习,基本上它是一个有一些产品的比尔,我应该可以制作账单,计算 IVA 等。
我有下一个架构:
create_table "bill_items", force: :cascade do |t|
t.integer "amount"
t.integer "product_id"
t.integer "bill_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["bill_id"], name: "index_bill_items_on_bill_id"
t.index ["product_id"], name: "index_bill_items_on_product_id"
end
create_table "bills", force: :cascade do |t|
t.string "user_name"
t.string "dni"
t.date "expiration"
t.float "sub_total"
t.float "grand_total"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "products", force: :cascade do |t|
t.string "name"
t.string "description"
t.float "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
比尔模型:
class Bill < ApplicationRecord
has_many :bill_items
has_many :products, through: :bill_items
accepts_nested_attributes_for :bill_items
end
BillItem 模型:
class BillItem < ApplicationRecord
belongs_to :product
belongs_to :bill
end
产品型号:
class Product < ApplicationRecord
has_many :bill_items
has_many :bills, through: :bill_items
end
ProductsController是普通的,脚手架生成的,没关系。
账单控制器:
class BillsController < ApplicationController
before_action :set_bill, only: [:show, :update, :destroy, :edit]
def new
@bill = Bill.new
@bill.bill_items.build
end
def create
@bill = Bill.new(bill_params)
byebug
@bill.save
end
private
def set_bill
@bill = Bill.find(params[:id])
end
def bill_params
params.require(:bill).permit(:user_name, :dni, { bill_items_attributes: [:product_id, :amount, :bill_id] })
end
end
最后是比尔的新观点:
<%= form_for(@bill) do |f| %>
<div>
<%= f.label :user_name %>
<%= f.text_field :user_name %>
</div>
<div>
<%= f.label :dni %>
<%= f.text_field :dni %>
</div>
<%= f.fields_for :bill_items do |fp| %>
<div>
<%= fp.label :product %>
<%= fp.collection_select :product_id, Product.all, :id, :name %>
</div>
<div>
<%= fp.label :amount %>
<%= fp.number_field :amount %>
</div>
<% end %>
<%= f.submit %></div>
<% end %>
这个问题非常具体,在 rails 5 中,当它尝试调用 @bill.save 时它会失败并且它会显示错误:
#<ActiveModel::Errors:0x007fd9ea61ed58 @base=#<Bill id: nil, user_name: "asd", dni: "asd", expiration: nil, sub_total: nil, grand_total: nil, created_at: nil, updated_at: nil>, @messages={:"bill_items.bill"=>["must exist"]}, @details={"bill_items.bill"=>[{:error=>:blank}]}>
但它在 Rails 4.2.6 中完美运行。 整个项目文件夹在这里:https://github.com/TheSwash/bill_app 目前在分支功能/bills_controller
有人知道发生了什么吗?
【问题讨论】:
-
这一切都在错误中说-
@messages={:"bill_items.bill"=>["must exist"]},所以它与RoR5无关。 -
@Vucko,我明白了,但这是 rails 4 中的问题,相同的实现可以在没有错误的情况下工作,这里的代码与 Rails 4 相同:github.com/TheSwash/bill_app_rails4
标签: ruby-on-rails-4 nested-attributes ruby-on-rails-5