我有一个名为“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是一个普通的,由脚手架生成,没关系。
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
最后比尔的新观点:
<%= 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
中有人知道发生了什么事吗?
答案 0 :(得分:1)
问题是bill_items验证
在rails 5中,默认情况下需要belongs_to关联
http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html