Seal
Seal

Reputation: 1060

Selecting which value to have a unique id on model

I have two models Deals and Restaurants

I want to display the deals for each restaurant. I do not want them linked on :restaurant_id, rather i want them linked on :restaurant_name.

What I cant figure out is how to link them on :restaurant_name in the controller

restaurant controller

def show
    @restaurant = Restaurant.find(params[:id])
    @deals = @restaurant.deals
end



show.html.erb

<% restaurant.deals.each do |deal| %>
       <h2><center><%= deal.day %></center></h2>
<% end %>

Any Ideas?

Upvotes: 0

Views: 40

Answers (2)

engineersmnky
engineersmnky

Reputation: 29308

If you must which might I say seems like a bad idea because if the name changes the chain breaks.

class Restaurant 
   has_many :deals, foreign_key: "restaurant_name", primary_key: "name"
end
class Deals
   belongs_to :restaurant, foreign_key: "restaurant_name", primary_key: "name"
end

This assumes that the model Restaurant uses name instead of restaurant_name but the concept is has_many foreign_key will be the key to use in the other table and primary_key will be the link in the current table.belongs_to foreign_key will be the key to use in the current table and primary_key will be the key in the other table.

Upvotes: 0

Jared Beck
Jared Beck

Reputation: 17528

I want to display the deals for each restaurant. I do not want them linked on :restaurant_id, rather i want them linked on :restaurant_name.

From a database perspective, assuming a relational database, your deals table will have a foreign key that references restaurants. Now that you know what to call it, this part of the belongs_to documentation should answer your question:

:foreign_key

Specify the foreign key used for the association. By default this is guessed to be the name of the association with an “_id” suffix ...

Now that you know how to implement your association, I should point out that many restaurants in the world share the same name, so restaurant_name may be a poor choice of foreign key.

Upvotes: 1

Related Questions