SitePoint Sponsor

User Tag List

Results 1 to 2 of 2

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Nov 2003
    Location
    Phoenix, AZ.
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Simply Rails 2 - Extended Question - Vote Once per Story?

    So I've been going through the Simply Rails 2 book and built the example app and have been playing around, extending and modifying it for practice.

    I have been struggling for a couple days on how-to see if a user has voted on the story while loading the Stories#index without having to do a separate sql call for each story fetched (I figured that out). I don't think it's optimal to do a all those sql queries on index load.

    Since the tables all have relationships I'd think it would be possible but can't figure it out. Any thoughts?

    If you don't have the book the tables and relevant cols are as follows:

    table stories (belongs_to :user, has_many :votes)
    id
    user_id

    table users (has_many: stories, has_many :votes)
    id

    table votes (belongs_to: stories, belongs_to :user)
    id
    story_id
    user_id

    When I load the 10 (20, 30) articles from the Stories#index I would like to know if the logged_in? user has voted on the story. Once again without doing a sql call for each story.

    * Note I've added a UNIQUE index on votes table for [story_id, user_id] so they can't vote twice already.

    Thx in advance

  2. #2
    SitePoint Enthusiast
    Join Date
    May 2008
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What you're looking for is Eager Loading, here's a Railscast on it:

    http://railscasts.com/episodes/22-eager-loading


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •