3

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..

3 Answers 3

2

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!

Sign up to request clarification or add additional context in comments.

7 Comments

Thats the issue, I don't know what I am trying to do via rails. What I am trying to do overall is make a post/get via ajax through jquery. And get a response back in json. With PHP and JavaScript this is the simplest of things in the world to do, but Rails rails seems to make it damn near impossible. And not being able to find an example of what I want doesnt make it any easier. Best thing I can find but not even remotely close requires me to submit a form go to a different page, handle the data redirect based on that and so on and so forth, im trying to do this all without reloading the page
Nah, you don't need to do that. You can still use AJAX and post to the page you're on, and get a JSON object back. You don't need to do a redirect_to to refresh the page, but know that it can cause "errors" in some cases if you don't. For example, flash messages won't show up if they are set and the page isn't explicitly changed.
@chris getting JSON back from AJAX is very easy to do with Rails. There are many good Rails + AJAX examples on the web. Here is a similar question to yours stackoverflow.com/questions/5223699/….
@chris I know it's easy to get lost when learning a new language/platform. Maybe it will help if you can simplify your problem. Where are you stuck right now and what is the very next step you need want to take? Do you have your main page setup? Are you making AJAX calls that fail?
@chris I threw together a quick example. I hope it can help if you still get stuck in places. Best of luck! git://github.com/WizardOfOgz/ajax_json_test.git github.com/WizardOfOgz/ajax_json_test
|
2

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.