Reputation: 627
I have 4 tables, customer
, customer_site
, site
and connection
. customer
and site
have many customer_sites
and a site
has many connections
. This has all been set up in my models. Now i'm trying to have a view for each customer, showing every connection linked to that customer. This is what i have in my view:
<% @connection.each do |l| %>
<tr>
<td><%= l.interface %></td>
<td><%= l.device %></td>
<td><%= l.speed %></td>
<td><%= l.site.name %></td>
</tr>
<% end %>
and this is my controller:
def show
@customer = Customer.find(params[:id])
@connection = Connection.all(where connection.site.customer_site.customer.id == params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @customer }
end
end
obviously the @connection
part isn't correct, i'm just not sure what I need to put in there to link the records correctly...
Upvotes: 0
Views: 1146
Reputation: 782
As @Matt mention in his comment, the easiest way is to use has_many
associations with :through
option.
You can read more about this in Rails guides.
class Site < ActiveRecord::Base
has_many :customer_sites, foreign_key: :site_id
has_many :connections
end
class CustomerSite < ActiveRecord::Base
belongs_to :site
belongs_to :customer
end
class Customer < ActiveRecord::Base
has_many :customer_sites, foreign_key: :customer_id
has_many :sites, through: :customer_sites
has_many :connections, through: :sites
end
In controller:
def show
@customer = Customer.find(params[:id])
@connections = @customer.connections
...
end
Let me know, if it is not clear enough.
Upvotes: 1