简体   繁体   中英

Ruby On Rails jQuery AJAX Post

Ok, in PHP I can do this in 5 minutes. With Rails I am completely lost. I am so new to Rails and I have a requirement to do more advanced stuff with it then I am comfortable with currently. The Big guy decided lets go Rails from PHP. So its crash course learning. Fun times..

I understand from the javascript side making the post/get with jquery remains the same. On the ruby side however I am completely lost. What do I need to do in order to do a post/get to a Rails App. How would I define my controller? Lets say from the HTML side I am posting

input1 and input2 standard jquery $.post with a JSON request for data back. With php I would make a simple controller like:

public function myFormPostData(){
    $errors = "none";
    $errorMsg = "";
    if($_POST['input1'] == ""){$errors = "found"; $errorMsg .= "Input 1 Empty<br>";}
    if($_POST['input2'] == ""){$errors = "found"; $errorMsg .= "Input 2 Empty<br>";}

    if($errors == "found"){ $output = array("error" => "found", "msg" => $errorMsg); }
    else{
        $output = array("error" => "none", "msg" => "Form Posted OK!!"); 
    }
  echo json_encode($output);
}

but in ruby I dunno how to translate that concept. I'm open to suggestions and good practices. Grant it the above is a super mediocre rendition of what I am needing to do I would sanitize things more than that and all else, but it gives the idea of what I am looking for in Rails..

First, you need to tell Rails that a certain page can accept gets and posts.

In your config/routes.rb file:

get 'controller/action'
post 'controller/action'

Now that action in that controller (for example, controller "users" and action "index") can be accessed via gets and posts.

Now, in your controller action, you can find out if you have a get or post like this:

def index
    if request.get?
        # stuff
    elsif request.post?
        # stuff
        redirect_to users_path
    end
end

Gets will look for a file corresponding to the name of the action. For instance, the "index" action of the "users" controller will look for a view file in app/views/users/index.html.erb

A post, however, is usually used in conjunction with the redirect (like in the above example), but not always.

First of all, Rails 3 has a nice feature called respond_with . You might check out this Railscast episode that talks about it. http://railscasts.com/episodes/224-controllers-in-rails-3 . The examples he uses are great if you are dealing with resources.

Having said that, I'll give you an example with a more traditional approach. You need to have a controller action that handles requests which accept JSON responses.

class MyController < ApplicationController
  def foo
    # Do stuff here...
    respond_to do |format|
      if no_errors? # check for error condition here
        format.json { # This block will be called for JSON requests
          render :json => {:error => "none", :msg => "Form Posted OK"}
        }
      else
        format.json { # This block will be called for JSON requests
          render :json => {:error => "found", :msg => "My bad"}
        }
      end
    end
  end
end

Make sure that you have a route set up

post '/some/path' => "my#foo"

Those are the basics that you will need. Rails gives you a lot for free, so you may find that much of what you are looking for already exists.

If you post a more concrete example of what you are trying to you might get even better advice. Good luck!

its hard at first to understand that you have to do things "the rails way", because the whole philospohy of rails is to enforce certain standards. If you try to fit PHP habits in a rails suit, it will just tear apart. The Rails Guides are your best friend here...

To be more specific about your problem, you should try to build something from ActiveModel . ActiveModel lets you use every feature ActiveRecord has, except it is meant to be used to implement non-persistent objects.

So you can create, say, a JsonResponder model:

class JsonResponder
  include ActiveModel::Validations

  validates_presence_of :input_1, :input_2

  def initialize(attributes = {})
    @attributes = attributes
  end

  def read_attribute_for_validation(key)
    @attributes[key]
  end
end

In your controller, you now create a new JsonResponder :

 # this action must be properly routed, 
 # look at the router chapter in rails 
 # guides if it confuses you
 def foo 
     @responder = JsonResponder.new(params[:json_responder])

     respond_to do |format|
       if @responder.valid?
          # same thing as @wizard's solution
          # ...
       end
     end
 end

now if your your input fields are empty, errors will be attached to your @responder object, same as any validation error you can get with an ActiveRecord object. There are two benefits with this approach :

  • all of your logic is kept inside a model of its own. If your response has to be improved later (process a more complicated request for instance), or used from different controllers, it will be very simple to reuse your code. It helps keeping your controllers skinny , and thus is mandatory to take a real advantage out of MVC.

  • you should be able (maybe with a little tweaking) to use rails form helpers, so that your form view will only have to be something vaguely like this :

(in the equivalent of a "new" View)

<% form_for @responder do |f| %>
   <%= f.input_field :field_1 %>
   <%= f.input_field :field_2 %>
   <%= f.submit %>
 <% end %>

feel free to ask for more precisions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM