Findind模型属于具有has_many通过关联的两个模型

时间:2016-05-10 14:49:55

标签: ruby-on-rails ruby ruby-on-rails-4

我的应用程序包含subtaskssubattributesweights

subtask可以有很多subattributes 来自 weights,可以有很多weights

subattribute可以有很多subtasks 来自 weights,可以有很多weights

weight可以同时属于subtasksubattribute

现在我正试图循环收集打印重量。但是,我正在解决如何获得具体权重的问题。这就是我所拥有的:

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

任何建议。这是我的第一个rails应用程序,我没有设计后端,因为我个人认为将权重作为子属性中的字段更容易。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

试试这个:

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