开发者

rails and namespaced models issue

Using rails 3/3.1 I want to store invoices with their items (and later more associations like payments, etc…).

So in a first approach I set up the models like this:

class Invoice < ActiveRecord::Base
  has_many :invoice_items
end

class InvoiceItem < ActiveRecord::Base
  belongs_to :invoice
end

And the routes likes this:

resources :invoices do
  resources :invoice_items
end

I chose InvoiceItem instead of Item because I already have a model named Item and I somehow want to namespace the model to invoices. But this name has the huge disadvantage that one has to use invoice.invoice_items instead of a intuitive invoice.items. Also the generated url helpers look real ugly, for example "new_invoice_invoice_item_path(invoice)" (notice the double invoice_invoice).

So I changed to namespaced models like this:

class Invoice < ActiveRecord::Base
  has_many :items, :class_name => "Invoice::Item"
end

class Invoice::Item < ActiveRecord::Base
  belongs_to :invoice
end

And the routes likes this:

resources :invoices do
  resources :items, :module => "invoice"
end

Now the assocation is named nicely and also the url helpers look pretty. But I can't use dynamic urls (ex. [:new, invoice, :item]) anymore, because the controller is set to "invoice_item" instead of "invoice/item".

I wonder how other people solve this problem and what I'm doing wrong. Or is this simply a bug in rails 3.0.7/ 3.1.rc?

EDIT: Sorry, I seems I didn't correctly express my concern. My model Item is not related to Invoice::Item. Order::Item is also not related to Item nor Invoice::Item. An Invoice::Item can only belong to one invoice. An Order::Item can only belong to an Order. I need to namespace - but why doesn't rails properly suppo开发者_如何学Gort namespacing out of the box? Or what am I doing wrong with namespacing?

Corin


If an order item and an invoice item are not the same object in the real world then I would name them differently rather than trying to namespace, for example OrderItem and InvoiceItem - this will keep things clearer as your codebase grows and avoid the need to make sure you use the right namespace everywhere you reference an Item.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜