Oleg Pasko
Oleg Pasko

Reputation: 2911

Rails 3.2 ajax example with params in controller

How to create ajax in next example:

In controller:

def index
    if params[:p] == "one"
        @record = "Hello, 1!"
    elsif params[:p] == "two"
        @record = "Hello, 2!"
    else
        @record = "something else"
    end
end

In view (hellos controller, index action):

<%= link_to "One", hellos_path(:p => "one") %>
<%= link_to "Two", hellos_path(:p => "two") %>
<%= render :partial => 'record' %>

Partial _record.html.erb:

<%= @record %>

That's all. All actions in index controller and only params are changing. I don't want to reload full page - only record partial with new controller variable.

How to "AJAXize" it? :)

Upvotes: 1

Views: 1059

Answers (1)

Erez Rabih
Erez Rabih

Reputation: 15788

1- Add :remote => true to your links:

<%= link_to "One", hellos_path(:p => "one"), :remote => true %>

2- create a view index.js.erb with:

$("#your_div").html("<%= render :partial => "record" %>")

3- create a div with the id your_div in your index.html.erb. This div will be populated with the @record object.

Upvotes: 4

Related Questions