I have a story model that has many posts. I list the stories in an index view without each story’s posts. When a user clicks on one of the stories in the index view I want to load that story’s posts via calling stories/(story_id)/posts using the ajax .load function, and make sure to put the posts into that story’s correct div (created by “<%= div_for(story, “posts_bucket_for”) do %>”)
The problem is, I don’t know how to pass the correct story_id to the .load function or how to make sure that the resulting posts are loaded into the correct posts_bucket_for.
Here’s my _story.html.erb file:
<%= div_for(story) do %>
<%= div_for(story, "heading_for") do %>
<span class=story_title>
<%= story.title.titleize %>
</span>
<span class=story_post_amount>
# of posts: <%= story.posts.length %>
</span>
<% end %>
<%= div_for(story, "posts_bucket_for") do %>
<% end %>
Here’s my PostController#index action
def index
@story = Story.find(params[:story_id])
@posts = @story.posts
respond_with(@posts, :api_template => :public, :root => :posts)
end
Any help would be greatly appreciated!!!
Here is one way to implement a solution (this is for Rails 3).
According to the Rails documentation for
div_for,div_for(story, :class => "story")will produce HTML that looks like:So, with jQuery, you could run something like:
For your buckets, I would not use another
div_for(story). This would result in you having twodivson the page with the same ID. Instead, I would do something like this:And then, in jQuery
The remaining task is to have a controller action handle the AJAX request and return the posts to be inserted onto the page.
You’ll also want to create a partial to render the posts. In my example, this would be
views/stories/_posts.html.erb.This is a lot of new learning material if you haven’t dealt with AJAX+Rails before, so here are a couple useful tutorials: here and here.