Rashed Al-Julaibi
Rashed Al-Julaibi

Reputation: 281

Rails - Need help displaying database records associated with has_many :through in "show" page

I have quite a simple problem, but cant figure out how to solve it. I have two models: Shop and Mall, which are associated through a join table called MallShops. When a new shop is created, I have the option to link the shop to whatever malls currently existing in the database through check boxes. The issue is after I have saved the shops, I dont know how to display the malls that have been associated to that shop in the shops show page. This is my code:

Models:

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

Join table:-

create_table "malls_shops", force: :cascade do |t|
  t.integer "shop_id"
  t.integer "mall_id"
end

Shop form:-

<%= 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 %>

Upvotes: 0

Views: 38

Answers (1)

Wes Foster
Wes Foster

Reputation: 8900

It's as simple as calling for the association from a given relation. For example:

shops_controller.rb

def show
  @shop = Shop.find(params[:id])
end

show.html.erb

<% @shop.malls.each do |m| %>
  <%= m.name %><br>
<% end %>

Calling the malls method will return all of the associated malls to that given shop.

Upvotes: 1

Related Questions