0

I am using link_to tag to change the validity:

  <%= link_to "Mark as " + (doc.is_valid ? "invalid" : "valid"), 
                  :action =>'change_validity',:id => doc.id %>

Here, is_valid is a field in a table with boolean value. When it is true link will show as "Mark as invalid". When I click the link it will call the method "change_validity" method in controller. The method will toggle the is_valid field and show "Mark as valid" in view.

This one I want to do using AJAX. I tried to using link_to_remote. But I couldn't get it. Can anyone explain how to do it???

2 Answers 2

1

Make one partial page. _preview.html.erb and put below code into your partial view

<%= link_to_remote "Mark as " + (doc.is_valid ? "invalid" : "valid"), :update => "update", :url => { :action => "change_validity", :id => doc.id } %>

In your main view file.put below code

<div id="update">
    <%= render :partial => "preview", :locals => { :doc => @doc} %>
</div>

In your controller should have below code

def change_validity
// do stuff here
render :partial => "preview", :locals => { :doc => @doc}, :content_type => 'text/html'
end
Sign up to request clarification or add additional context in comments.

5 Comments

second update is id of div. when you click first time, it does ajax call to your controller action, there you write a code to change valid into your db, then render partial view with latest update into db that html then display into div
it is not working.. I think ajax call is not happening.. when I click on link nothing is happening. I added logger line in controller it is not coming in log file.
if you have firefox browser, then install firebug addon and in this addon you can see all ajax requests with data
Browser console is throwing error called => ReferenceError: Ajax is not defined
can you paste what are js files included into your page ? it seems ajax related js files not rendering on your page.
0

link_to_remote is not available in Rails 3. Add :remote => true to your link.

link_to "Mark as " + (doc.is_valid ? "invalid" : "valid"), 
              change_validity_path(:id => doc.id), :remote => true

EDIT: for rails < 3 try

link_to_remote(
        "Mark as " + (doc.is_valid ? "invalid" : "valid"),
        :url => {:action => "change_validity", :id => doc.id},
        :update => "your_div_id",
        :html => {:class => "something"}
      )

3 Comments

change_validity is method in my controller not a model.
could you explain what should be the update and html fields ??
:update needs the e.g. id of your <div> where the response html code should go. Or you can do it on the controller side using "render :update do |page| ... end" block.

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.