【问题标题】:Passing model instance variable from one controller to another in redirect_to in Rails在 Rails 的 redirect_to 中将模型实例变量从一个控制器传递到另一个控制器
【发布时间】:2013-05-07 16:25:48
【问题描述】:

我使用的是 Rails 版本 3.2.10。我正在尝试将具有许多属性的模型实例变量从一个动作传递到不同控制器中的另一个动作。

我尝试了很多事情,但没有得到解决方案。

第一个控制器方法:

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

结束

我必须将@ applicant 变量从第一个控制器访问到第二个控制器方法。

【问题讨论】:

  • @applcant 是这里的错字,或者是您的实际代码中出现问题的根本原因。

标签: ruby-on-rails


【解决方案1】:

您不能那样做...您必须在第一个操作中将对象存储在 DB 中,然后在第二个操作中检索它。

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

【讨论】:

  • 但我没有将其保存在数据库中。我已经使用omniauth 来进行身份验证和收集详细信息,我将其存储在@applicant 中,我必须在不同的控制器中使用它来显示带有预填充值的表单。所以我必须在不保存它们的情况下访问那里的山谷。请给我另一条路。
【解决方案2】:

您应该将大量此类逻辑从控制器移到模型中。

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

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

【讨论】:

  • 但是通过这样做,如何访问变量?
  • 你从控制器中的create方法调用这个方法,然后你重定向到你需要的页面。我会稍微修改一下这个问题,向您展示它是如何工作的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 2019-05-31
相关资源
最近更新 更多