Ruby on Rails:在视图之间保存控制器实例变量的正确方法?

时间:2018-01-19 18:37:31

标签: ruby-on-rails

这可能不是正确的做事方式,但老实说我不知道​​该怎么办。

我正在创建一个导入系统,它将序列化的字符串作为输入,将其反序列化为ActiveRecord对象,然后向用户显示一个确认屏幕,显示将导入的所有项目以及当用户按下“保存”时“按钮,项目全部保存。

我完成了反序列化,并且我已经构建了确认页面,以便显示将要导入的每个项目。

最后一步是按下按钮,按下后将保存每个项目。

我认为这就像我认为的那样简单:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP=localhost
; http://php.net/smtp-port
;smtp_port=25
sendmail_path = C:/xampp/sendmail/sendmail.exe -t
; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = me@example.com
; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
;sendmail_path =
; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail().
;mail.force_extra_parameters =
; Add X-PHP-Originating-Script: that will include uid of the script followed by the filename
mail.add_x_header=On
; The path to a log file that will log all mail() calls. Log entries include
; the full path of the script, line number, To address and headers.
;mail.log =
; Log mail to syslog (Event Log on Windows).
;mail.log = syslog

这在我的控制器中:

<%= button_to 'Save Items', :action=> :save_items %>

(@ items_to_save是一个ActiveRecord对象数组)

但是,因为button_to似乎实际上是在发出新请求,所以只要按下按钮就会丢失@items_to_save。

是否有更好的方法将视图上的按钮绑定到控制器操作,以便不会触发新请求并且我的项目不会丢失?

1 个答案:

答案 0 :(得分:0)

您需要将一些信息添加到您的链接(参数)。

@items_to_save丢失是对的。控制器全局变量@仅可供视图访问 - 而不是使用其他操作后的其他方式。

因此,您可以首先选择项目中的所有ID,将它们放入数组中,将它们添加到按钮参数,渲染时,然后在单击按钮时迭代它们。

# deserialize it into ActiveRecord objects - action
# don't know how your looks - i hope it's understandable 
...
@items_ids = @active_record_objects.ids
...

然后在您的视图中,您会将它们添加到button_to,以便您可以在控制器操作save_items中使用这些ID。

<%= button_to "Save Items", action: :save_items, params: {ids: @items_ids} %> 

现在你可以迭代它们并保存!

def save_items
  Item.where(id: params[:ids]).each(&:save)
end