Megan Woodruff
Megan Woodruff

Reputation: 194

Findind model that belongs to two models with a has_many through association

I have an application that has subtasks, subattributes, and weights.

A subtask can have many subattributes via weights and can have many weights.

A subattribute can have many subtasks via weights and can have many weights.

A weight can belong to both a subtask and a subattribute.

Right now I am trying to loop through the collection print the weight. However, I am having issues acutally figuring out how to get the specific weights. Here's what I have:

<% @subtasks.each do |subtask| %>
   <% @subattributes.each do |subattribute| %>
      <% if subattribute.subtasks.include (subtask) %>
           #find the weight of that subattribute that's associated with that subtask
      <% else %>
         #create a new weight associated with the subattribute and subtask
      <% end %>
   <% end %>
  <% end %>

Any suggestions. This is my first rails app and I didn't design the backend because I personally would have thought it easier to just have weight be a field in subattribute. Any help would be greatly appreciated.

Upvotes: 0

Views: 37

Answers (1)

dp7
dp7

Reputation: 6749

Try this:

<% @subtasks.each do |subtask| %>
   <% @subattributes.each do |subattribute| %>
      <% if subattribute.subtasks.include?(subtask) %>
         #find the weight of that subattribute that's associated with that subtask
           <% Weight.where(subattribute_id: subattribute.id,subtask_id: subtask.id).first %>
      <% else %>
          #create a new weight associated with the subattribute and subtask
          <% Weight.create(subattribute_id: subattribute.id,subtask_id: subtask.id) %>
      <% end %>
  <% end %>
<% end %>

Upvotes: 1

Related Questions