如何从do块访问实例变量?

时间:2014-03-25 08:00:11

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

以下代码不起作用。它说undefined method 'table_name' for nil:NilClass

@members = Members.all

table member_list_rows do      
  if @members.table_name == members
    row(0).background_color = '3498db'
  end
end

完整代码

class MemberPdf < Prawn::Document
  def initialize(members, view, allcount)
    super(top_margin: 50)
    if members.size != allcount
      @warn = " (Not all members)"
    else
      @all = " All"
    end
    text "Showing#{@all} #{members.size} Members", size: 18, style: :bold, align: :center, color: "636363"
    text "#{@warn}", size: 11, align: :center, color: "858585"
    @members = members
    @view = view
    member_list
  end

  def member_list
    move_down 20
    table member_list_rows do
      self.row(0).align = :center
      if @members.table_name == "members"
        row(0).background_color = '3498db'
      else

      end

      row(0).text_color = "FFFFFF"
      self.row_colors = ["DDDDDD", "FFFFFF"]
      self.header = true
      #self.cell.text_color = "B3B3B3"
      row(0).columns(0).style size: 20
    end
  end

  def member_list_rows
    [["Name", "Awardunit", "Address", "Contact", "Level of Entry", "Current Award", "Disabled?"  ]] +
    @members.map do |member|
      [member.name, member.awardunit.name, member.address, member.name, member.entrylvl, member.currentaward, @view.yesno(member.disabled)]
    end
  end
end

会员控制器

    if params[:commit] == "Clear"
        params[:q] = nil
    end

    respond_to do |format|
        format.html
        format.pdf do
            pdf = MemberPdf.new(Member.search(params[:q]).result.order( 'name ASC' ), view_context, Member.all.size)
            send_data pdf.render, filename: "Members_List.pdf", type: "application/pdf", disposition: "inline"
        end
    end

3 个答案:

答案 0 :(得分:3)

归因于@members是零。你做错了。

更改此

@members = Members.all #Wrong

@members = Member.all #Right

永远记住,型号名称应为单数

这些被称为命名约定。有关详情,请参阅这些样式指南(RubyRails

答案 1 :(得分:1)

最有可能table方法正在改变上下文,在该上下文中,您无法再访问@members实例变量。这可以通过以下示例代码轻松实现:

def do_stuff(&block)
  cls = Class.new
  cls.instance_eval(&block)
end

@test_var = "test_var"

do_stuff { puts @test_var }

您将不会收到任何内容,因为@test_var中不存在cls

答案 2 :(得分:0)

我不确定你在做什么&#34; table member_list_rows&#34;。没有那个。 但在第三行中,它应该是

if @members.table_name == "members"