简体   繁体   English

在RAILS中将模型从一个控制器动作传递到另一个控制器动作的替代方法

[英]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。

persons_controller 人员_控制器

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个动作编写的,相当于我需要在其上显示nameage 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.

相关问题 Rails:如何在同一个控制器中将值从一个动作传递到另一个动作 - Rails: How to pass value from one action to another in the same controller 将对象从一个控制器动作传递给另一个 - Pass an object from one controller action to another Rails将变量从模型传递到另一个控制器 - rails pass variable from model to another controller 从一个控制器调用Rails 5动作 - Calling a Rails 5 action from one controller to another 使用控制器操作从一个模型检索数据并将数据保存到另一模型-Rails 4 - Use controller action to retrieve data from one model and save data to another model - Rails 4 Rails通过不同对象的形式将参数从一个控制器动作传递到另一个 - Rails pass parameter from one controller action to another through form of different object Rails link_to将:id从show传递到另一个控制器动作 - Rails link_to pass :id from show to another controller action Ruby on Rails 4-将答案从一个控制器传递到另一个控制器 - Ruby on Rails 4 - Pass answer from one controller to another controller 将一个控制器动作映射到另一个动作导轨上 - Map one controller action on another action rails 在Ruby on rails上将数据从一个控制器提交到另一个控制器模型 - Submit data from one controller to another controller model in Ruby on rails
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM