相當寬泛的問題,這裏就是我想要做的:
#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以及它們內部的東西感到困惑。 –