Rails:与3个模型的多对多关系

时间:2010-08-10 04:09:14

标签: ruby-on-rails rails-activerecord has-and-belongs-to-many

我的情况是产品供应商购物清单估值

shopping_list 包含许多估价,每个产品,特定的供应商

我的模型如下:

class Product < ActiveRecord::Base
  has_many :valuations
  has_many :shopping_lists, :through => :valuations
end

class Supplier < ActiveRecord::Base
  has_many :valuations
  has_many :shopping_lists, :through => :valuations
end

class ShoppingList < ActiveRecord::Base
  has_many :valuations
  has_many :products, :through => :valuations
  has_many :suppliers, :through => :valuations
end

class Valuation < ActiveRecord::Base
  belongs_to :product
  belongs_to :supplier
  belongs_to :shopping_list
end

我的 routes.rb 是:

  map.resources :shopping_lists do |shopping_list|
    shopping_list.resources :valuations
  end

  map.resources :product

  map.resources :supplier

我想知道这是否是最好的解决方案,无论如何我想要的是用户可以创建任意数量的列表,每个列表都有多个估值。

第一次创建购物清单时,其中还包含至少一个评估。然后,用户可以向shopping_list添加/删除估价。

我想要一个简单而优雅的解决方案,没有Ajax回调。

controllers / views / routes 角度来看,最好的方法是什么? 或者我应该完全改变我的架构吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

刚从Ryan Bates找到两个优秀的资源:

http://asciicasts.com/episodes/196-nested-model-form-part-1

http://asciicasts.com/episodes/197-nested-model-form-part-2

让我们看看是否能完成这项工作!

//更新:工作得很好!