Rails 多对多关系如何建立二维表

yeyong14 · 2014年04月29日 · 最后由 yeyong14 回复于 2014年05月02日 · 3232 次阅读

三个模型,目前我是这样做的,不知道对不对。还是有其他的方法。

#迭代出来类似这样的应该怎么做出来的

city_name |  product_1 | product_2 
 city_1     |     1           |    2
 city_2     |     1           |    2
#product.rb
  has_many :items
  has_many :cities, :through: items

#city.rb
  has_many :items 
  has_many :products, through: :items

#item.rb
  belongs_to :product
  belongs_to :city

#controller

def index
  @products = Product.all
  @cities = City.all
end

#view 
  @products.each do |product|
     @cities.each do |city|
#这里应该怎么做的?
    end
  end

这么写逻辑就混乱了。多对多由中间表转化为一对多,应该在在一个 def 里只操作一对多或多对一的关系。你这么写,中间表还建它干嘛??

@weichen0 请教一下如何才能实现,给点思路吧,谢谢

需要 登录 后方可回复, 如果你还没有账号请 注册新账号