简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM