在Rails4中,如何在一个控制器动作中分配变量并在另一个控制器动作中使用变量的值 [英] In Rails4 How to assign variables in one controller action and use the value of it in another controller action

查看:77
本文介绍了在Rails4中,如何在一个控制器动作中分配变量并在另一个控制器动作中使用变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Ruby on Rails 4,我有一个UI,用户可以在其中从服务器上的目录路径中选择一个视频文件.然后,他们单击一个在文件上运行媒体信息的按钮,并显示视频的xml以及解析xml中的某些数据值,并将该值分配给@variables并将其显示在UI html页面中.这些都是在动作/方法评估媒体"中完成的.页面重新加载时,它确定该文件是否已保存,并允许用户将文件名,路径和媒体信息属性保存到mysql中的表中.当您单击保存按钮时,它将调用acton/方法"save_file".当我尝试将这些变量值分配给模型类字段以插入表中(在控制器内).不会读取这些值.它仅插入空值.如何 我可以在'evaluate_media'操作中分配这些变量值,也可以用于'save_file'操作或同一控制器中的任何其他操作吗?基于它们的设置和定义方式,我认为它们在模型/控制器对象"file_alias_tfile"的范围内可用.

using Ruby on Rails 4, I have a UI where the user can select a video file from a directory path on a server. They then click a button that runs media info on the file and displays the xml for the video along with parsing certain data values from the xml and assigning the value to @variables and displaying it back in the UI html page. This is all done in the action/method 'evaluate media'. When the page loads back it determines if this file has been saved or not and allows the user to save the filename, path, and media info attributes to a table in mysql. When you click the save button it calls the acton/method 'save_file'. When I try to assign these variable values to the model class fields to insert into the table (within the controller). The values are not read. It only inserts nulls. How can I have these variable values assigned in the 'evaluate_media' action also be available for the 'save_file' action or any other action within the same controller? Based on how they were setup and defined, I thought they were availble within the scope of the model/controller object 'file_alias_tfile'.

在"save_file"操作中,这是我尝试分配值的3种不同方式:

In the 'save_file' action here are the 3 different ways I tried to assign the value:

    full_path = params[:filepath2]  <--This one puts a NULL into the table  
    src_location = @radio_button_value  <--This one puts a NULL into the table
    directory = "#{@dir_path_choice}"  <--This one doesn't even get called into the insert script and nothing is inthe column on insert. (I don't get errors and a record does geet inserted with the other good values.)into the table

这是我的save_file操作/方法代码,在这里我试图将变量值分配给模型字段:

Here is my save_file action/method code where I am trying to assign my variable values to the model fields:

  def save_file    

        src_location = @radio_button_value
        directory = "#{@dir_path_choice}"
        full_path = params[:filepath2]
 #       "#{@filepathname}"
        full_filename = "#{@filepath}"
        alias_code = "#{@file_alias}"
        validate_status = "#{@file_status}" 
        error_msg = "#{@file_msg}"
        video_alias_match = "#{@msg_dtl1}" 
    audio_alias_match = "#{@msg_dtl2}" 
    video_format = "#{@video_format}" 
    video_bitrate = "#{@video_bitrate}" 
    video_width = "#{@video_width}"
    video_height = "#{@video_height}" 
    video_framerate = "#{@video_framerate}" 
    video_aspect_ratio = "#{@video_aspectratio}" 
    video_scan_type = "#{@video_scantype}"
    video_scan_order = "#{@video_scanorder}" 

    @file_alias_tfile = FileAliasTfile.new( :src_location => src_location, :directory => directory, :full_path => full_path, :full_filename => full_filename, :file_ext => '', 
                                                  :assigned_status => 'Unassigned', :file_status => 'Saved', :alias_code => alias_code, :validate_status => validate_status, :error_msg => error_msg, 
                                                  :video_alias_match => video_alias_match, :audio_alias_match => audio_alias_match, :video_format => video_format, :video_bitrate => video_bitrate, 
                                                  :video_width => video_width, :video_height => video_height, :video_framerate => video_framerate, :video_aspect_ratio => video_aspect_ratio, 
                                                  :video_scan_type => video_scan_type, :video_scan_order => video_scan_order, :video_alias_code => '', :audio_alias_code => '', 
                                                  :bus_prod_initiative_id => 0, :status => 'Active', :start_date => DateTime.now.to_date, :end_date => '', :deleted_b => 0, 
                                                  :created_by => 'admin', :updated_by => 'admin')

@file_alias_tfile = FileAliasTfile.create(file_alias_tfile_params)

if @file_alias_tfile.save
  redirect_to mainpages_home_path, :notice => "The file alias validation has been saved."
else
  redirect_to alias_mainpages_home_path, :notice => "The file alias validation has been saved."

#render =索引" 结尾 结束

# render = "index" end end

这里是'evaluate_media'方法,其中定义了save_file中上面调用的值:

Here is the 'evaluate_media' method where the values called above in the save_file are defined:

def评估媒体 @state ='发布' @radio_button_value =参数[:位置]

def evaluate_media @state = 'post' @radio_button_value = params[:location]

 #Determine if file chosen has been saved to database yet.
 @stored_file = FileAliasTfile.where(:full_path => params[:filepath2], :deleted_b => 0).first

 if @stored_file.present?
    @file_exists_flag = 'Y'
    @file_exists_msg = 'This File and Alias has been saved in application.'
 else
    @file_exists_flag = 'N'
    @file_exists_msg = 'This File and Alias has NOT been saved in application yet.'
  end

      root_dir = '/watchfolder/miniprod/hot/'
      provider_dir = ""

   #Store selected value for re-display on post.
   @selected_filepath = params[:filepath2]

filepath = File.join(root_dir,provider_dir,params [:filepath])

   @filepath = File.join(params[:filepath2])  

   @media_xml = ::MediaInfo.call(@filepath)  #Filepath is sent in from the index html
   @alias_xml = ::AliasGenerator.call(@media_xml)

   @media_xml_for = ""
   @alias_xml_for = ""
   REXML::Document.new(@media_xml).write(@media_xml_for, 1)
   REXML::Document.new(@alias_xml).write(@alias_xml_for, 1)
   alias_parse_doc = ""
   media_parse_doc = ""
   alias_parse_doc = REXML::Document.new(@alias_xml)  
   media_parse_doc = REXML::Document.new(@media_xml) 


   #parse Alias XML Doc   
   # @aliasgen_ver = alias_parse_doc.elements.each("/aliasGenerator vr=/text()") { |e| e }
   @aliasgen_ver = REXML::XPath.each(alias_parse_doc, "/aliasGenerator vr=/text()") { |element| element }    
   @file_alias = REXML::XPath.each(alias_parse_doc, "*//alias/text()") { |element| element }
   @file_status = REXML::XPath.each(alias_parse_doc, "*//error/text()") { |element| element }
   @file_msg = REXML::XPath.each(alias_parse_doc, "*//error_m/text()") { |element| element }
   @msg_dtl1 = REXML::XPath.each(alias_parse_doc, "*//closestvideoalias/text()") { |element| element }
   @msg_dtl2 = REXML::XPath.each(alias_parse_doc, "*//closestaudioalias/text()") { |element| element }

   #parse Video Media Info XML Doc  
    @filepathname = REXML::XPath.each(media_parse_doc, "*//Complete_name/text()") { |element| element }  
    @video_format = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Format/text()") { |element| element }
    @video_bitrate = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Bit_rate/text()") { |element| element }  
    @video_width = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Width/text()") { |element| element } 
    @video_height = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Height/text()") { |element| element }
    @video_aspectratio = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Display_aspect_ratio/text()") { |element| element } 
    @video_framerate = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Frame_rate/text()") { |element| element } 
    @video_scantype = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Scan_type/text()") { |element| element } 
    @video_scanorder = REXML::XPath.each(media_parse_doc, "//track[@type='Video']/Scan_order/text()") { |element| element }   

   #parse Audio Media Info XML Doc 
  #  @audio_track = REXML::XPath.each(media_parse_doc, "//track[@type= 'Audio']/track/text()") { |element| element } 
 #   @track_array = REXML::XPath.each(media_parse_doc,(@audio_track)) do {|track| track.elements["Bit_rate"].text }
  #   @bitrate = track.elements["Bit_rate"].text
  #  end
    #@audio_tracknum = REXML::XPath.each(media_parse_doc, "//track[@type='Audio']/track streamid=/text()") { |element| element } 
   # @audio_format = REXML::XPath.each(media_parse_doc, "//track[@type='Audio']/Format/text()") { |element| element } 
   # @audio_bitrate = REXML::XPath.each(media_parse_doc, "//track[@type='Audio']/Bit_rate/text()") { |element| element }  
   # @audio_numchan = REXML::XPath.each(media_parse_doc, "//track[@type='Audio']/Width/text()") { |element| element } 
   # @audio_language = REXML::XPath.each(media_parse_doc, "//track[@type='Audio']/Display_aspect_ratio/text()") { |element| element } 

   render :action => :index

结束

能否请您提供一个示例,说明如何正确设置变量以跨操作传递和/或如何在插入物中将变量正确分配给数据库?

Can you please provide me an example of how I can either setup my variables correctly to pass across actions and/or how to properly assign them in the insert to the database?

感谢您的帮助!

推荐答案

我在另一个搜索问题中找到了答案,但仍然有一个悬而未决的问题.

I found the answer in another question for my search but it still leaves an open question.

这是其他问题和答案的链接,以获取更多详细信息: 针对控制器的所有操作的相同实例变量

Here is the link for the other question and answer for more details: Same instance variable for all actions of a controller

基本上,它给了我2种方法.如果我的一个动作不是从另一个动作呈现的,并且这两个方法都需要访问值,那么我将需要定义另一个方法,在此我分配变量,然后让save_file和valuate_media方法都调用此新定义的方法,因此它们也可以访问变量.这是示例,该问题解决了索引并显示了共享相同变量的方法.

Basically it gave me 2 approaches. If my one action is not rendering from the other, and both methods need to access the values, then I will need to define another method where I assign the variables and then have both save_file and evaluate_media methods call this newly define method so they too can access the variables. Here is the example where the question addressed the index and show methods sharing the same variable.

def index
  set_up_instance_variable
end

def show
  set_up_instance_variable
end

private

def set_up_instance_variable
  @some_instance_variable = foo
end

另一种解决方案是使用before_filter:

The other solution is using the before_filter:

您可以使用前置过滤器为多个操作定义实例变量,例如:

You can define instance variables for multiple actions by using a before filter, e.g.:

class FooController < ApplicationController
  before_filter :common_content, :only => [:index, :show]

 def common_content
    @some_instance_variable = :foo
  end
end

现在,@ some_instance_variable将可通过从索引或显示操作呈现的所有模板(包括部分模板)进行访问.

Now @some_instance_variable will be accessible from all templates (including partials) rendered from the index or show actions.

这篇关于在Rails4中,如何在一个控制器动作中分配变量并在另一个控制器动作中使用变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆