简体   繁体   English

Rails-如何将一个“商店”与多个“购物中心”同时关联?

[英]Rails - How to associate a “Shop” with more than one “Mall” at the same time?

I am making a simple rails app which acts as a directory of all Malls in Kuwait and Shops within that mall. 我正在制作一个简单的Rails应用,它充当科威特所有购物中心和该购物中心内商店的目录。 I created a Shop model and Mall model and made the following association:- 我创建了商店模型和购物中心模型,并建立了以下关联:-

class Shop
has_many_and_belongs_to :malls

class Mall
has_many :shops

As the same shop can exist in more than one mall, I would like a way for me to link a shop with more than one mall at the same time. 由于同一家商店可以存在于多个购物中心中,所以我想为我提供一种将商店与多个购物中心同时链接的方法。 How can I make it so that a shop automatically appears under many different malls when I go to that malls show page, without having to individually create the same shop each time for each mall. 我如何做到这一点,以便当我进入该购物中心的显示页面时,商店会自动出现在许多不同的购物中心下,而不必每次都为每个购物中心分别创建同一个商店。 So in other words I need to be able to choose which malls the shop belongs to while im creating a new shop, and then have that shop appear in the malls that I previously specified. 因此,换句话说,我需要能够在创建新商店时选择该商店所属的购物中心,然后使该商店出现在我先前指定的购物中心中。

Update: Explain assigning the shop to a particular mall in the creation process. 更新:说明在创建过程中将商店分配给特定的购物中心。 For example when I create a new shop, how do I then specify that it belongs to Mall A and Mall B but not Mall C, and then have them appear in the corresponding Malls show page? 例如,当我创建一个新商店时,如何指定它属于Mall A和Mall B但不属于Mall C,然后将它们显示在相应的Malls显示页面中?

You can have a HABTM association to handle this, 您可以使用HABTM关联来处理此问题,

   class Shop < ActiveRecord::Base
     has_and_belongs_to_many :malls
   end

   class Mall < ActiveRecord::Base
     has_and_belongs_to_many :shops
   end

Create migrations for Shop and Mall table, you need to have a migration to create a table which works as a join between shop and mall. 为Shop and Mall表创建迁移,您需要进行迁移以创建用作Shop和Mall之间的联接的表。 It should contain mall_id and shop_id as attributes. 它应包含mall_id和shop_id作为属性。

rails g migration create_mall_shops

Update for controller code: 控制器代码更新:

 shop = Shop.find(params[:id])
 mall = Mall.find(params[:mall_id])
 shop.malls << mall

shop.malls will give you an array of malls related to shop. shop.malls将为您提供一系列与shop相关的购物中心。 Now, coming back as you expect, in shop.malls array, push only mall object A and B. So mall C will never be related to shop 现在,按预期返回,在shop.malls数组中,仅推送商城对象A和B。因此商城C永远不会与shop相关

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM