相当宽泛的问题,这里就是我想要做的:
#app/models/invoice.rb
class Invoice < ActiveRecord::Base
belongs_to :user
has_many :line_items
has_many :items, through: :line_items
accepts_nested_attributes_for :line_items
end
#app/models/line_item.rb
class LineItem < ActiveRecord::Base
belongs_to :invoice
belongs_to :item
end
#app/models/item.rb
class Item < ActiveRecord::Base
belongs_to :company
has_many :line_items
has_many :invoices, through: :line_items
end
- -
#app/models/user.rb
class User < ActiveRecord::Base
has_many :invoices
end
这将是基准级“发票”关联结构 - 您的可以在其上构建/users
。
你的路线等可以如下:
#config/routes.rb
resources :invoices
#app/controllers/invoices_controller.rb
class InvoicesController < ApplicationController
def new
@invoice = current_user.invoices.new
@invoice.line_items.build
end
def create
@invoice = current_user.invoices.new invoice_params
@invoice.save
end
end
那么你的看法会是这样的:
#app/views/invoices/new.html.erb
<%= form_for @invoice do |f| %>
<%= f.fields_for :line_items do |l| %>
<%= f.text_field :quantity %>
<%= f.collection_select :product_id, Product.all, :id, :name %>
<% end %>
<%= f.submit %>
<% end %>
这将创建相应的@invoice
,与您就可以打电话如下:
@user.invoices.first
除此之外,我没有足够的地方具体信息可帮助明确
谢谢你的反馈,我喜欢你迄今为止的建议。我会尝试这个,一旦我得到它的工作,或者如果我有任何问题(希望不是),会让你知道。干杯 –
Jus想知道应该在项目表和line_item表内进行什么。我的意思是item_name价格数量&ect。就像我的情况一样,我喜欢current_company和调用现有的项目,我会这样current_company.items,所以我需要更改为current_company.line_items?我对物品和line_item以及它们内部的东西感到困惑。 –