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

yeyong14 · April 29, 2014 · Last by yeyong14 replied at May 02, 2014 · 3234 hits

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

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

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

可以建立一个视图,参照:http://pivotallabs.com/rails-sql-views-1/

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

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

You need to Sign in before reply, if you don't have an account, please Sign up first.