Ruby on rails 4 嵌套属性在rails 5中失败,但在rails 4中有效
我有一个叫做“BillApp”的练习,基本上是一个有一些产品的账单,我应该可以制作账单,计算IVA,等等 我有下一个模式:Ruby on rails 4 嵌套属性在rails 5中失败,但在rails 4中有效,ruby-on-rails-4,nested-attributes,ruby-on-rails-5,Ruby On Rails 4,Nested Attributes,Ruby On Rails 5,我有一个叫做“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 "upda
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
class Bill
BillItem模型:
class BillItem < ApplicationRecord
belongs_to :product
belongs_to :bill
end
class BillItem
产品型号:
class Product < ApplicationRecord
has_many :bill_items
has_many :bills, through: :bill_items
end
类产品
ProductsController是由scaffold生成的普通控件,这无关紧要
BillsController:
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
class BillsController
最后,法案提出了新的观点:
<%= 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 5中,默认情况下,属于所需的关联
所有这些都在错误中说明-@messages={:“bill\u items.bill”=>[“必须存在”]}
,因此它与RoR5无关。@Vucko,我明白了,但这是rails 4中的问题相同的实现没有错误,这里是rails 4中的相同代码: