Question

i have this problem, i cant seem to figure it out. Okey, i have a form, where user can enter values, than this from is sent to controller via POST method using ajax remote: true than i need to validate user input. This form will not be saved in to database, so this controller dont have model. How can i go about this? And after its validated how can i respond with errors to view?

Here is the view (i am using HAML):

= form_tag({action: "calculate"}, :method => :post, remote: true) do
  .value#grace_field
    = label_tag t('value', :scope => 'controller_scope_name')
    = select_tag "value", options_for_select([[0, 0],[1, 1]])
  = submit_tag t('calculate', :scope => "controller_scope_name")
.section#results

Here is the controller:

class HomeController < ApplicationController

  def calculate

    #.... here is some logic which i canot publish. 

    @results = {
      #some results
    }

    respond_to do |format|
      format.js {}
    end
  end

end

And here are responding files calculate.js.erb and partial _results.html.haml:

1

$("#results").html("<%= escape_javascript(render 'results') %>");

2

 %ul
      - @results.each do |key, value|
        %li= t("results.#{key}") + ": #{value}"

Everything works fine, but now i need to validate this form....I read something about using ActiveRecord methods for plain rails object. How could i do this?

Was it helpful?

Solution

You can include ActiveModel::Validations in plain objects and use validators as in ActiveRecords. Check this railscast for more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top