我得到NoM​​ethodError,我不知道为什么

时间:2017-05-22 22:06:18

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

我正在创建一个联接表,它会告诉我哪个员工卖掉了哪个漫画。当我输入我的员工姓名时,它给了我这个错误

NoMethodError in Showemployeesales#employeesaleout
undefined method `name_id' for nil:NilClass

这是我的控制器代码

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

以下是我输入视图的代码" employeenamein"

   <h1>Showemployeesales#employeenamein</h1>
   <p>Find me in app/views/showemployeesales/employeenamein.html.erb</p>
    <%= form_tag(showemployeesales_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 %>

这是我输出视图的代码

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

     <center><table width = 65% border = 1> 
     <tr> <th> Comic Name </th><th> Comic ID </th></tr>   
     <% @sale_list.each do |m| %>     

     <tr> <td> <%= m.product.name_id %> </td> <td> <%= m.product.id_no %> 
     </td></tr>
     <% end %> </table> </center><br /> <br />

我的架构下的产品表

   create_table "products", force: :cascade do |t|
   t.string   "name_id"
   t.integer  "id_no"
   t.datetime "created_at", null: false
   t.datetime "updated_at", null: false
   end

我做错了什么?

1 个答案:

答案 0 :(得分:0)

你真的太复杂了。

要在REST中查看数据,请使用GET请求,而不是发布。命名是......不好。

# routes.rb
resources :employees do
  resouces :sales, only: :index, module: :employees
end
# app/controllers/employees/sales_controller.rb
class Employees::SalesController
  # /employees/:employee_id/sales
  def index
    @employee = Employee.includes(:sales)
                        .find(params[:id])
    @sales = @employee.sales
  end
end

只需创建一份员工列表,并为每个员工添加一个链接:

<% @employees.each do |e| %>
  <%= link to e.name, employee_sales_path(e) %>
<% end %>

或使用autocomplete的表单。但真的KISS在你的水平。

# app/views/employees/sales/index.html.erb
# use CSS instead of <center> and missusing <br> tags - it's not 1998
<h1>These are the Sales for <%= @employee.name %></h1>
<table> 
  <tr>
    <th>Comic Name</th>
    <th> Comic ID</th>
  </tr>   
  <% @sales.each do |s| %>     
  <tr>
    <td><%= s.product.name_id %></td>
    <td><%= s.product.id_no %></td>
  </tr>
  <% end %> 
</table>