rails从另一个表中提取数据

时间:2015-04-24 01:26:10

标签: ruby-on-rails

<% @checkouts.reverse.each do |checkout| %>
  <tr>
    <td><%= checkout.radio_num %></td>
    <th colspan="3"></th>
    <td><%= checkout.badge %></td>
    <th colspan="3"></th>
  </tr>
    <% @staffs.each do |staff| %>
        <% if checkout.badge == staff.badge %>
        <tr>
            <td><%= staff.name %></td>
            <th colspan="3"></th>
            <td><%= staff.dept %></td>
        </tr>
        <% end %>
    <% end %>   
  <tr>
    <td><%= link_to 'Edit', edit_checkout_path(checkout) %></td>
    <td><%= link_to 'Destroy', checkout, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>

我是ruby on rails的新手,我正在尝试为无线电创建一个结账/退货应用程序。在我的观看/结账中是否需要做一些事情以允许访问我的员工表?

我在第8行得到错误

  

未定义的方法`徽章&#39;为零:NilClass

这是被问到的控制器代码

class StaffsController < ApplicationController

def index
@staffs = Staff.all
end

def show
@staff = Staff.find(params[:id])
end

def new
@staff = Staff.new
end

def create
@staff = Staff.new(staff_params)
if @staff.save
  redirect_to(:action => 'index')
else
  render('new')
end
end

def edit
@staff = Staff.find(params[:id])
end

def update
@staff = Staff.find(params[:id])
if @staff.update_attributes(staff_params)
  redirect_to(:action => 'show', :id => @staff.id)
else
  render('index')
end
end

def delete
@staff = Staff.find(params[:id])
end

def destroy
Staff.find(params[:id]).destroy
redirect_to(:action => 'index')
end

private

def staff_params
params.require(:staff).permit(:badge, :name, :dept)
end

end

谢谢!

2 个答案:

答案 0 :(得分:0)

您正在使用@checkout(第9行),但您声明的局部变量(第1行)实际上称为checkout

同样,您使用的是@staff,但您实际可用的变量是staff

因此对于第9行,你应该改为:

   <% if checkout.badge == staff.badge %>

请注意,您不需要在模板中使用@variables,除非它们是在控制器中设置的内容。

在这种情况下,看起来你在控制器中设置了变量:@staffs@checkouts ......它们似乎是数组。 @staff@checkout were not set up in the controller - they are just local variables, and so are correctly named without the @`

答案 1 :(得分:0)

有问题的视图是checkout / index视图,它将引用CheckoutController的索引操作/方法。这是由于轨道约定优于配置。如果在该控制器方法/操作上未定义@staffs实例变量,则将抛出nil:NilClass错误。

你的控制器看起来应该是这样的。

class CheckoutController < ApplicationController
  def index
    # avoid calling ActiveRecord query methods in the view
    # Checkout.all.reverse or
    @checkouts = Checkout.order(created_at: :desc)
    @staffs = Staff.all
  end
end

避免视图中的逻辑也是一种好习惯。作为初学者,在视图中放置逻辑感觉很自然,但随着时间的推移,您将看到您的视图变得更加复杂,并且认知开销也会增加。

Helper方法是开始封装视图中某些逻辑的好地方。

module CheckoutHelper
  def equal_badge?(checkout_badge, staff_badge)
    checkout_badge == staff_badge
  end
end

使用

在视图中调用它
<% if equal_badge(checkout.badge, staff.badge) %>

rails中的另一个很酷的技巧是渲染集合的部分内容(当前存储在人员和结帐实例变量中的内容)。

创建一个包含

的_staff_list.html.erb
  <% if equal_badge(checkout.badge, staff.badge) %>
    <tr>
      <td><% staff.name %>
      <!-- etc, etc -->
  <% end %>

在结帐/索引视图中,通过

呈现部分
<%= render partial: "checkouts/staff_list", collection: @staffs, locals: { checkout: checkout } %>

这比你要求的要多,但我希望这有点帮助。

相关问题