[英]Passing model instance variable from one controller to another in redirect_to in Rails
I am using Rails version 3.2.10.我正在使用 Rails 版本 3.2.10。 I am trying to pass a model instance variable with many attributes in it from one action to another action in different controller.
我试图将一个包含许多属性的模型实例变量从一个动作传递到不同控制器中的另一个动作。
I have tried many things, but not getting a solution.我尝试了很多事情,但没有得到解决方案。
First controller method:第一种控制器方法:
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
Second controller method:第二种控制器方法:
def newProfile
@job = Job.find_by_id(params[:id])
puts @job.id
@applicant = Applicant.new
@applicant = @applicant
end结尾
I have to access the @ applicant
variable from first controller into second controller method.我必须从第一个控制器访问
@ applicant
变量到第二个控制器方法。
You just can't do that... You will have to store your object in DB in the first action and then retrieve it in the second one.你不能那样做......你必须在第一个动作中将你的对象存储在 DB 中,然后在第二个动作中检索它。
With a redirect_to, you can pass arguments as you would in a url for example, not complete objects.使用redirect_to,您可以像在url 中一样传递参数,而不是完整的对象。 Here you would pass the saved object id in the redirect_to.
在这里,您将在redirect_to 中传递保存的对象ID。
You should move a lot of this logic from the controller into the model.您应该将很多这种逻辑从控制器移到模型中。
So, I would have a model method:所以,我会有一个模型方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.