Rails控制器:调用关联的模型记录到索引视图

时间:2019-01-21 20:00:20

标签: ruby-on-rails database model-view-controller activerecord controller

此控制器活动记录查询存在问题。我有一个称为Submissions的模型,每个Submission都有一个与其关联的AgentActivity。我试图使用数据库查询简单地显示一行中的所有“提交”字段及其旁边的关联“代理活动”,但是这样做却出错了,这太简单了吗?:

@agent_activities = @submissions.find(:agent_activity)

提交索引操作

def index
 @agent_activities = @submissions.find(:agent_activity)
 @submissions = 
 SubmissionLocation.includes(:submission).where(location_id: 
 current_agent.Company_Business_Location).map(&:submission)
end

     <% @submissions.each do |submission| %>
  <tr>
    <td><%= submission.First_Name %></td>
    <td><%= submission.Last_Name %></td>

    <% if user_signed_in? %>
    <td><%= submission.Phone %></td>
    <td><%= submission.Email %></td>
    <%else%>
      <% end %>
    <td><%= submission.Desired_Location %></td>
    <td><%= submission.number_of_beds %></td>
    <td><%= submission.number_of_occupants %></td>
    <td><%= submission.Rent_price_per_month_gbp %></td>


    <% if user_signed_in? %>
    <td><%= submission.Max_move_in_date %></td>
    <td><%= submission.Tenant_Occupation %></td>
    <td><%= submission.Contact_me_on %></td>
    <td><%= submission.Furnished %></td>
    <td><%= submission.Current_Address %></td>
    <td><%= submission.Property_Requirements %></td>

    <%else%>
      <% end %>

      <% Array(@agent_activities).each do |agent_activity|%>

    <td><%= agent_activity.Status %></td>
    <td><%= agent_activity.Notes %></td>

     <% end%>
   <td><%= link_to 'See More', submission %></td>
     <% end %>

提交模型

   class Submission < ApplicationRecord
   belongs_to :user, :optional => true


   has_many :agent_activities, inverse_of: :submission
   has_many :agents, through: :agent_activities

   accepts_nested_attributes_for :agent_activities, :reject_if=> proc 
  {|attributes| attributes[:entry].blank?}, :allow_destroy => true

  has_many :submission_locations

  attr_accessor :location_1, :location_2, :location_3
  end

代理活动模型

   class AgentActivity < ApplicationRecord

   belongs_to :submission, :optional => true, inverse_of: 
   :agent_activities #has submission_id foreign key in table
   belongs_to :agent, :optional => true, inverse_of: :agent_activities 

   end

1 个答案:

答案 0 :(得分:0)

您要在尝试调用@submissions之后分配find。您需要取消顺序。

编辑:同样,您使用的关联错误。看来您没有SubmissionLocation模型。

应该是:

def index
 @submissions = Submission.where() #fill this query out
end

然后在视图上遍历submissions时,可以调用submission.agent_activities