Suggestions on how to use ActiveRecord model/controller without saving a record?

时间:2016-07-11 20:07:57

标签: ruby-on-rails ruby activerecord

This might be an odd question, and hard to convey the subject in a blurb title, but here goes:

I have a simple Rails app, that stores a set of info. Users can create reports to extract information they care about - there is a "Report" model, validations are run, and these reports are saved. When a report is run, @report is sent to a reporting method, the information is retrieved, and rendered.

But now I want to create an ad hoc reporting feature, that does NOT save the report - the app should accept the report params, validate them, and then immediately run the report, all without saving.

To do this, I have tried to re-use my existing new/edit form, I've created an ad_hoc method that does @report.new(report_params), calls the model validations, and then tried to render :reporting @report. etc. I'll make a little progress, but then run in to a new roadblock.

Before I post code looking for help on any particular issue, I wanted to get some feedback on the best approach to do this sort of ad hoc reporting. Any suggestions?

To summarize, I would like to:

  • Have an ad hoc form that looks identical to my new/edit form
  • Use the model validations I have (making sure the start date is before the end date, etc)
  • Have a report run immediately after validation/submission

I know I could do a hacky version where some reports are tagged as ad hoc, hide them in the UI, and have a rake task delete these, etc. But is there an elegant approach to this I am missing?

2 个答案:

答案 0 :(得分:0)

Here's what I'd probably do:

#reports_controller.rb
def adhoc_checker
  @report = Report.new(report_params)
  if @report.valid?
    @report.run
    # render it to view or something, redirect may not be your friend here because report isn't persisted
  else
    # inform the user that report isn't valid, send valid report
  end
end

#report.rb
def run
  # perform the operations you want to perform here
end

This should work because AR#valid? method runs the validation and reports if they are valid. This method runs before your model is saved too.

Let me know if that helps or other clarifications

答案 1 :(得分:0)

But is there an elegant approach to this I am missing?

Yes, it should be easy to switch functionality based on whether or not it is an "ad hoc" report.

You have not explained the UX for the ad hoc report. If you have a checkbox (for example), you can do something like:

def create
  if params[:ad_hoc]
    ...
  else
    # send report to reporting method
  end