2013-05-07 77 views
1

我正在使用钢轨版本3.2.10
我想将具有许多属性的模型实例变量从一个动作传递到另一个动作在不同的控制器中。在redirect_to rails中将模型实例变量从一个控制器传递给另一个控制器?

我已经尝试了很多东西,但没有得到解决方案。

第一控制器方法

def create 
if current_user 
    auth = request.env["omniauth.auth"] 
    @applicant = Applicant.new 
    if (auth['provider'] == "linkedin") 
    puts auth.info.image 
    linkedinProfileImport(auth) 
    @applcant.first_name = auth.info.first_name 
    @applcant.second_name = auth.info.last_name 

    redirect_to controller => 'job_applicants', :action => 'newProfile' , :id => params[:id] 
    end 

第二控制器的方法

def newProfile 
@job = Job.find_by_id(params[:id]) 
puts @job.id 
@applicant = Applicant.new 
@applicant = @applicant 

我必须从第一控制器访问@申请人变量到第二控制器的方法。
帮我在这请
在此先感谢

回答

4

你就不能这样做......你必须在你的数据库的对象存储在第一个动作,然后在第二个检索。

使用redirect_to,您可以像在URL中传递参数那样传递参数,而不是完整的对象。在这里,您可以将保存的对象ID传递给redirect_to。

+0

,但我没有保存在数据库中。我已经使用omniauth进行身份验证和收集详细信息,我存储在@applicant中,我必须在不同的控制器中使用它显示带有预填充值的表单。所以我不得不在那里存取那些价值。请给我另一种方式。 – 2013-05-07 16:40:26

0

您应该将很多这种逻辑从控制器移到模型中。

所以,我想有一个模型方法:

def create #in the controller 
    if current_user 
    auth = request.env["omniauth.auth"] 
    @applicant = Applicant.create_from_omniauth_hash(auth) 

    redirect_to controller => 'job_applicants', :action => 'newProfile' , :id => params[:id] 
end 



class Applicant < ActiveRecord::Base 
    def self.create_from_omniauth_hash(auth) 
    applicant = Applicant.new 
    if (auth['provider'] == "linkedin") 
     puts auth.info.image 
     linkedinProfileImport(auth) 
     applicant.first_name = auth.info.first_name 
     applicant.second_name = auth.info.last_name 
    end 
    create_new_profile(applicant) 
    applicant.save! 
    end 

    def create_new_profile(applicant) 
    applicant.job = "job" 
    end 
end 
+0

但通过这样做,如何访问变量? – 2013-05-07 16:41:30

+0

你可以从控制器的'create'方法调用这个方法,然后你重定向到你需要的页面。我会稍微编辑一下这个问题,告诉你它是如何工作的。 – Solomon 2013-05-07 16:43:38

+0

好的。做到这一点。它会帮助我很多 – 2013-05-07 16:47:06

相关问题