如何在Ruby的同一类中的一个方法中使用一个变量到另一个方法中的变量? [英] How to use a variable from one method to other in a same class in Ruby?

查看:87
本文介绍了如何在Ruby的同一类中的一个方法中使用一个变量到另一个方法中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Ruby的新手.我的控制器中有以下代码. 期望的行为:- 我想在编辑页面上的视图中显示验证错误字符串.因此,我将这些错误放入变量中.当验证失败时,我想在编辑方法中使用该变量,以便可以在编辑页面视图中显示该变量.

I am new to Ruby. I have a below code in my controller. Desired Behaviour :- I want to display validation error string to my views on edit page. So I am putting those errors in a variable. When validation fails then I want to use that variable in my edit method, so that I can display that on my edit page view.

观察到的行为:- create 方法中有一个变量 @vpinerr .我想在 edit 方法中使用该变量.我尝试使用类变量(@@ vpinerr)并使用空字符串(@@ vpinerr =")对其进行初始化,然后在编辑方法中此变量的值变为空.

Observed behaviour :- There is a variable @vpinerr in create method. I wan to use that variable in edit method. I have tried to use the class variable (@@vpinerr) and initialized it with an empty string (@@vpinerr = "") then the value of this variable becomes empty in edit method.

require 'rho/rhocontroller'
    require 'helpers/browser_helper'

    class LeadController < Rho::RhoController
      include BrowserHelper

      # GET /Lead
      def index
        @leads = Lead.find(:all)
        render :back => '/app'
      end

    # GET /Lead/new
      def new
        @lead = Lead.new
        render :action => :new, :back => url_for(:action => :index)
      end


      def create
        # Update
        if Lead.find(@params['id'])
            @lead = Lead.find(@params['id'])
            # array of objects
            @leadadd = LeadAddress.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                    )
            @leadcon = LeadContact.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                        )


            #hash of hashes
            leadaddressArray = @params['leadaddress']


            arr1 = @leadadd.count - 1

            for i in 0..arr1
              j=i.to_s
              @leadaddHash = @leadadd[i]
              leadaddressHash = leadaddressArray[j]


              if leadaddressHash['removed'] == "1"
                singleadd = LeadAddress.find(:first,
                                        :conditions => {:object => leadaddressHash['object']}
                                    )
                singleadd.destroy if singleadd
              else
                #validation
                vpin = leadaddressHash['pincode']
                #validation check
                if vpin =~ /^[[:digit:]]+$/
                  @leadaddHash.update_attributes(leadaddressHash) if @leadaddHash
                else
                  err = 1
                  @vpinerr = "Pincode is invalid"
                end           
              end
            end


            leadconArray = @params['leadcontact']
            arr2 = @leadcon.count - 1  
            for k in 0..arr2
              z=k.to_s
              @leadconHash = @leadcon[k]
              leadContact = leadconArray[z]
              if leadContact['removed'] == "1"
                singlecon = LeadContact.find(:first,
                                        :conditions => {:object => leadContact['object']}
                                    )
                singlecon.destroy if singlecon
              else
                @leadconHash.update_attributes(leadContact) if @leadconHash
              end

            end


            @lead.update_attributes(@params['lead']) if @lead
            if err == 0
              redirect :action => :index
            else
              redirect :action => :edit, :id => @lead.object, :vpin =>@vpinerr
            end 

        else
        # Create
            err = 0

            # validation
            vlead = @params['lead']
            vfirstname = vlead['firstname']
            vlastname = vlead['lastname']
            vage = vlead['age']


            #validation check
            if (vfirstname =~ /^[[:alpha:][:blank:]]+$/) and (vlastname =~ /^[[:alpha:][:blank:]]+$/) and (vage =~ /^[[:digit:]]+$/) 
              @lead = Lead.create(@params['lead'])
              @key = @lead.object
            else
              err = 1
              @basicerr = "Basic Details are invalid"
            end

            if @params['leadaddress']
              leadaddressArray = @params['leadaddress']
              arrcount = leadaddressArray.count
              for i in 1..arrcount
                j=(i-1).to_s
                leadaddressHash = leadaddressArray[j]
                #validation
                vpin = leadaddressHash['pincode']
                #validation check
                if vpin =~ /^[[:digit:]]+$/
                  @leadAdd = LeadAddress.create(leadaddressHash)
                  @leadAdd.parentKey = @key
                  @leadAdd.save()
                else
                  err = 1
                  @vpinerr = "Pincode is invalid"
                end
              end
            end

            if @params['leadcontact']
              leadconArray = @params['leadcontact']
              arrcount2 = leadconArray.count 
              for k in 1..arrcount2
                h=(k-1).to_s
                leadconHash = leadconArray[h]
                #validation
                vhome = leadconHash['home']
                vmobile = leadconHash['mobile']
                vemail = leadconHash['email']
                #validation check
                if (vhome =~ /^[[:digit:]]+$/) and (vmobile =~ /^[[:digit:]]+$/) and (vemail =~ /\A([\w+\-]\.?)+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i)
                  @leadcontact = LeadContact.create(leadconHash)     
                  @leadcontact.parentKey = @key
                  @leadcontact.save()
                else
                  err = 1
                  @contacterr = "Contact Details are invalid"    
                end           
              end
            end

            if err == 0
              redirect :action => :index
            else
              redirect :action => :edit, :id => @lead.object
            end      
        end
      end


    # GET /Lead/{1}
      def show
        @lead = Lead.find(@params['id'])
        @leadadd = LeadAddress.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                    )
        @leadcontact = LeadContact.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                        )

        if @lead
          render :action => :show, :back => url_for(:action => :index)
        else
          redirect :action => :index
        end
      end


      # GET /Lead/{1}/edit
      def edit
        @lead = Lead.find(@params['id'])
        @leadaddress = LeadAddress.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                    )
        @leadcontact = LeadContact.find(:all,
                                        :conditions => {:parentKey => @lead.object}
                                       )
        @vpinerr2 = @vpinerr


        if @lead
          render :action => :new, :back => url_for(:action => :index)
        else
          redirect :action => :index
        end
      end


    end

推荐答案

@开头的变量被视为实例变量,并且在类的实例中可用.您的控制器是一个类,在每个请求中,Rails都会实例化一个新的控制器实例.从这种意义上讲,当您请求创建操作时,将创建一个新实例,并在该实例中设置@vpinerr.当您将用户重定向到编辑操作时,将实例化其新请求和新控制器实例.由于创建操作和编辑操作的实例不同,因此在编辑操作中将没有@vpinerr的值.

Variables with a prepending @ are considered as instance variables and are available in a class's instance. Your controller is a class and with every request, Rails instantiates a new controller instance. In that sense, when you make a request to the create action, a new instance is created and @vpinerr is set in the instance. When you redirect the user to the edit action, its a new request and a new controller instance is instantiated. Since the instances from create action and edit actions are different, you won't have the value of @vpinerr in the edit action.

您还有其他选择.

  1. 类级变量.

在类上设置类级变量,并且在所有实例中都可用.任何以@@开头的变量都是类变量.随处更改为@@vpinerr,而不是@vpinerr.

Class-level variables are set on the class and are available in all instances. Any variable prepended with @@ are class variables. Change to @@vpinerr everywhere instead of @vpinerr.

这在您的情况下使用是错误的,因为您可能希望每个用户的值都不同,但是使用类变量也会保留其他用户的值,直到更改为止.阅读有关类变量的信息: http ://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby

This would be wrong to use in your case because, you could want it to be different for each user but using class variable will keep the value for other users too until its changed. Read about class variables: http://www.railstips.org/blog/archives/2006/11/18/class-and-instance-variables-in-ruby

  1. 会话变量.

会话变量用于在会话中保存变量.它们也可以在控制器之间共享.要设置会话变量session[:vpinerr] = "Some error"并使用它,您可以简单地调用session[:vpinerr].

Session variables are used to save variables within a session. They can be shared between controllers too. To set a session variable session[:vpinerr] = "Some error" and to use it, you can simple call session[:vpinerr].

这篇关于如何在Ruby的同一类中的一个方法中使用一个变量到另一个方法中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆