Rails - 需要帮助显示与 has_many 关联的数据库记录:通过 "show" 页面
Rails - Need help displaying database records associated with has_many :through in "show" page
我有一个很简单的问题,但不知道如何解决。我有两个模型:Shop
和 Mall
,它们通过名为 MallShops
的联接 table 关联。创建新商店时,我可以选择 link 通过复选框将商店添加到数据库中当前存在的任何购物中心。问题是在我保存了商店之后,我不知道如何在商店展示页面中显示与该商店相关联的购物中心。这是我的代码:
型号:
class Mall < ActiveRecord::Base
has_many :mall_shops
has_many :shops, :through => :mall_shops
end
class Shop < ActiveRecord::Base
has_many :mall_shops
has_many :malls, :through => :mall_shops
end
class MallShop < ActiveRecord::Base
belongs_to :shop
belongs_to :mall
end
加入table:-
create_table "malls_shops", force: :cascade do |t|
t.integer "shop_id"
t.integer "mall_id"
end
店铺形式:-
<%= form_for(@shop) do |f| %>
<div class="field">
<%= f.label "Which malls does it belong to?" %><br>
<% Mall.all.each do |mall| %>
<%= check_box_tag "shop[mall_ids][]", mall.id, @shop.malls.include?(mall) %>
<%= mall.name %><br>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
就像从给定关系中调用关联一样简单。例如:
shops_controller.rb
def show
@shop = Shop.find(params[:id])
end
show.html.erb
<% @shop.malls.each do |m| %>
<%= m.name %><br>
<% end %>
调用 malls
方法将 return 所有关联的购物中心到该给定商店。
我有一个很简单的问题,但不知道如何解决。我有两个模型:Shop
和 Mall
,它们通过名为 MallShops
的联接 table 关联。创建新商店时,我可以选择 link 通过复选框将商店添加到数据库中当前存在的任何购物中心。问题是在我保存了商店之后,我不知道如何在商店展示页面中显示与该商店相关联的购物中心。这是我的代码:
型号:
class Mall < ActiveRecord::Base
has_many :mall_shops
has_many :shops, :through => :mall_shops
end
class Shop < ActiveRecord::Base
has_many :mall_shops
has_many :malls, :through => :mall_shops
end
class MallShop < ActiveRecord::Base
belongs_to :shop
belongs_to :mall
end
加入table:-
create_table "malls_shops", force: :cascade do |t|
t.integer "shop_id"
t.integer "mall_id"
end
店铺形式:-
<%= form_for(@shop) do |f| %>
<div class="field">
<%= f.label "Which malls does it belong to?" %><br>
<% Mall.all.each do |mall| %>
<%= check_box_tag "shop[mall_ids][]", mall.id, @shop.malls.include?(mall) %>
<%= mall.name %><br>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
就像从给定关系中调用关联一样简单。例如:
shops_controller.rb
def show
@shop = Shop.find(params[:id])
end
show.html.erb
<% @shop.malls.each do |m| %>
<%= m.name %><br>
<% end %>
调用 malls
方法将 return 所有关联的购物中心到该给定商店。