Rails 3.0 example of a simple Ajax-based model property toggle
Ruby JavaScript
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
app
config
db
doc
lib/tasks
public
script
test
vendor/plugins
.gitignore
.rvmrc
Gemfile
README.markdown
Rakefile
config.ru

README.markdown

Simple example of toggling a model property via Ajax

We'll use an example of an article we can approve/un-approve.

Model generation

rails g scaffold Article name:string approved:boolean

Original article index view

<%= article.name %> <%= article.approved %> ...

Pull the approval info into a partial to keep changes localized.

<%= article.name %> <%= render :partial => 'approval' %> ...

Approved/unapproved link text helper

Create helper method to encapsulate the display of approved/unapproved status. For this example we'll just use text.

def approve_link_text(approvable) approvable.approved? ? 'Un-approve' : 'Approve' end

Two quick things to point out:

1) It's not tied to articles; it'll quack at anything with an "approved?" method. 2) I named the parameter something that should provide a hint to future devs.

Add a resource method to toggle the approved status

routes.db

resources :articles do get toggle_approve, :on => :member end

Article controller

(This isn't the final version yet.)

def toggle_approve @a = Article.find(params[:id]) @a.toggle!(:approved) render :nothing => true end

Change the approval template

<%= link_to approve_link_text(article), toggle_approve_article_path(article), :remote => true %>

Now if we refresh the page after clicking the link we'll see that the link text has changed. Approved articles will have an "Un-approve" link, un-approved articles an "Approve" link.

But refreshing is deeply unsatisfying.

Dynamic feedback, Part 1

Remember when fadey-yellow things were cool? Yeah, we're all about that.

In order to affect change on our page, we'll need to add some markup to both the index template, so we can highlight the entire row, and the approval helper, so we can change the link text.

Articles index page

<% @articles.each do |article| %>