我在Ruby on Rails中得到一个未定义的方法错误,我不知道为什么

时间:2017-05-21 15:23:58

标签: ruby-on-rails ruby-on-rails-3 cloud9

基本上我有两个名为Employees和Sales的表。我有一个表格,您输入员工姓名,它应该显示他们已售出的手机。每当我输入名称时,我都会收到此错误

undefined method `sales' for #<Employee:0x007f013e23fdc0>

它突出显示了下面显示的代码的@sale_list = r.sales部分(我的控制器)

class ShowEmployeeSalesController < ApplicationController
  def employeesaleout
    @employee_name = params[:employee_name_in]
    r = Employee.find_by_name_id(@employee_name)
    @sale_list = r.sales
  end
end

这是输入视图的代码:

<h2>
  Please enter the name of the Employee for whom you want to see the sales 
</h2>

<%= form_tag(show_employee_sales_employeesaleout_path, :controller =>  "ShowEmployeeSales", :action => "employeesaleout", :method => "post") do %>
  <div class="field">
    <%= label_tag :Employee_Name %><br />
    <%= text_field_tag :employee_name_in %>
  </div>

  <div class="actions">
    <%= submit_tag "Submit Employee Name" %>
  </div>
<% end %>

这是我输出视图的代码:

<h1>ShowEmployeeSales#employeesaleout</h1>
    <center>
      <h1>
        These are the Sales for <%= @employee_name %> 
      </h1>
    </center><br /> <br />

    <center>
      <table width = 65% border = 1> 
        <tr>
          <th> Phone Name </th>
          <th> Phone ID </th>
        </tr>   
        <% @sale_list.each do |m| %>     
          <tr> 
            <td> 
              <%= m.Mobile %> 
            </td> 
            <td> 
              <%= m.Employee %> 
            </td>
          </tr>
        <% end %> 
      </table> 
    </center><br /> <br />

我的所有表格都包含数据。

1 个答案:

答案 0 :(得分:1)

在您的Employee模型中,您应该:

class Employee < ActiveRecord::Base
  has_many :sales
end

并在您的Sale模型中:

class Sale < ActiveRecord::Base
   belongs_to :employee
end

此外,您的employee_id

中应该有一个列属性sales
t.integer :employee_id

快乐的编码:)