[英]Alternative ways to pass model from one controller action to another in RAILS
I have about 6-7 different actions within the same controller that get hit on each view loading. 我在同一个控制器中有大约6-7个不同的动作,每次加载视图时都会被击中。 How I'm doing this now is like so:
我现在的操作方式如下:
person_id
is passed into the URL. person_id
传递到URL。
person_id = params[:person_id]
people = PersonSearch.where(:person_id => person_id)
@response_people = people.map do |p|
{
:name => p.name,
:age => p.age
}
The above code snippet is written in 6-7 actions within my controller, which equates to 6-7 views that I need to display name
and age
on. 上面的代码段是在控制器中以6-7个动作编写的,相当于我需要在其上显示
name
和age
6-7个视图。
How could I look this person up by ID in my first view then track that specific person
model through each action without having to look him up and use a .map
method? 如何在第一个视图中通过ID查找此人,然后通过每个动作跟踪该特定
person
模型而不必查找他并使用.map
方法?
Create a function like this 创建一个这样的功能
def set_person
person_id = params[:person_id]
people = PersonSearch.where(:person_id => person_id)
@response_people = people.map do |p|
{
:name => p.name,
:age => p.age
}
end
And then at the top of your controller add this but replace :show and :edit with the controller actions you want to set person on. 然后在控制器的顶部添加此内容,但将:show和:edit替换为要设置人员的控制器操作。
before_action :set_person, only: [:show, :edit]
This will run the set_person function prior to each action you specify given you access to @response_people
in your views. 这将在您指定的每个操作之前运行set_person函数,从而使您可以在视图中访问
@response_people
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.