views:

36

answers:

2

I have created a blog application using Ruby on Rails and have just added an authentication piece and it is working nicely. I am now trying to go back through my application to adjust the code such that it only shows information that is associated with a certain user.

Currently, Users has_many :posts and Posts has_many :comments.

When a post is created I am successfully inserting the user_id into the post table. Additionally I am successfully only displaying the posts that belong to a certain user upon their login in the /views/posts/index.html.erb view. My problem is with the comments.

For instance on the home page, when logged in, a user will see only posts that they have written, but comments from all users on all posts. Which is not what I want and need some direction in correcting. I want only to display the comments written on all of the logged in users posts.

Do I need to create associations such that comments also belong to user? Or is there a way to adjust my code to simply loop through post to display this data.

I have put the code for the PostsController, CommentsController, and /posts/index.html.erb below and also my view code but will post more if needed.

class PostsController < ApplicationController

  before_filter :authenticate

  auto_complete_for :tag, :tag_name
  auto_complete_for :ugtag, :ugctag_name

  def index
    @tag_counts = Tag.count(:group => :tag_name, 
       :order => 'count_all DESC', :limit => 20)
       conditions, joins = {}, :votes

    @ugtag_counts = Ugtag.count(:group => :ugctag_name, 
       :order => 'count_all DESC', :limit => 20)
       conditions, joins = {}, :votes

    @vote_counts = Vote.count(:group => :post_title, 
          :order => 'count_all DESC', :limit => 20)
          conditions, joins = {}, :votes


       unless(params[:tag_name] || "").empty?
         conditions = ["tags.tag_name = ? ", params[:tag_name]]
         joins = [:tags, :votes]
       end
       @posts= current_user.posts.paginate(
                 :select => "posts.*, count(*) as vote_total", 
                 :joins => joins, 
                 :conditions=> conditions, 
                 :group => "votes.post_id, posts.id ", 
                 :order => "created_at DESC",
                 :page => params[:page], :per_page => 5)
        @popular_posts=Post.paginate(
                 :select => "posts.*, count(*) as vote_total", 
                 :joins => joins, 
                 :conditions=> conditions, 
                 :group => "votes.post_id, posts.id", 
                 :order => "vote_total DESC",
                 :page => params[:page], :per_page => 3)

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
      format.json { render :json => @posts }
      format.atom
    end
  end

  def show
    @post = Post.find(params[:id])


    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @post }
    end
  end

  def new
    @post = Post.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @post }
    end
  end

  def edit
    @post = Post.find(params[:id])
  end

  def create
    @post = current_user.posts.create(params[:post])

    respond_to do |format|
      if @post.save
        flash[:notice] = 'Post was successfully created.'
        format.html { redirect_to(@post) }
        format.xml  { render :xml => @post, :status => :created, :location => @post }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end

  def update
    @post = Post.find(params[:id])

    respond_to do |format|
      if @post.update_attributes(params[:post])
        flash[:notice] = 'Post was successfully updated.'
        format.html { redirect_to(@post) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @post.errors, :status => :unprocessable_entity }
      end
    end
  end


  def destroy
    @post = Post.find(params[:id])
    @post.destroy


    respond_to do |format|
      format.html { redirect_to(posts_url) }
      format.xml  { head :ok }
    end
  end
end

CommentsController

class CommentsController < ApplicationController

  before_filter :authenticate, :except => [:show, :create]

  def index

    @comments = Comment.find(:all, :include => :post, :order => "created_at DESC").paginate :page => params[:page], :per_page => 5

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @comments }
      format.json { render :json => @comments }
      format.atom
    end
  end

  def show
     @comment = Comment.find(params[:id])

     respond_to do |format|
       format.html # show.html.erb
       format.xml  { render :xml => @comment }
     end
   end

   # GET /posts/new
   # GET /posts/new.xml

   # GET /posts/1/edit
   def edit
     @comment = Comment.find(params[:id])
   end

   def update
     @comment = Comment.find(params[:id])

     respond_to do |format|
       if @comment.update_attributes(params[:comment])
         flash[:notice] = 'Comment was successfully updated.'
         format.html { redirect_to(@comment) }
         format.xml  { head :ok }
       else
         format.html { render :action => "edit" }
         format.xml  { render :xml => @comment.errors, :status => :unprocessable_entity }
       end
     end
   end


 def create
   @post = Post.find(params[:post_id])
   @comment = @post.comments.build(params[:comment])

   respond_to do |format|
     if @comment.save
       flash[:notice] = "Thanks for adding this comment" 
       format.html { redirect_to @post }
       format.js
     else
       flash[:notice] = "Make sure you include your name and a valid email address" 
       format.html { redirect_to @post }


   end
 end
end 







 def destroy
    @comment = Comment.find(params[:id])
    @comment.destroy



    respond_to do |format|
      format.html { redirect_to Post.find(params[:post_id]) }
      format.js

    end
  end

end

View Code for Comments

<% Comment.find(:all, :order => 'created_at DESC', :limit => 3).each do |comment| -%>
                <div id="side-bar-comments">
                    <p>
                        <div class="small"><%=h comment.name %> commented on:</div>
                        <div class="dark-grey"><%= link_to h(comment.post.title), comment.post %><br/></div>
                        <i><%=h truncate(comment.body, :length => 100) %></i><br/>
                        <div class="small"><i> <%= time_ago_in_words(comment.created_at) %> ago</i></div>
                    </p>
                </div>
            <% end -%>
+1  A: 

I believe you can set up another relation on user model

has_many :comments, :through => :posts

and then user @user.comments.

j.
Where exactly would I use the @user.comments? Do I make the adjustment in the view or the comments controller?
bgadoci
Ok, changed controller to @comments = current_users.comments.find... and that seemed to work when displaying /comments but how do I make the adjustment using the view code above for display on the /posts/index.html.erb page?
bgadoci
@bgadoci: you should load all data in controllers and show it in views. So in controller you can do `@user = current_user` and in view `<% @user.comments.each do |comment| %>` and so on. Or in controller add `@comments = @user.comments`. It doesn't really matter here in which way you will do it.
klew
You have `@posts= current_user.posts` on your `index` method (`posts` controller), so you can use `@posts.comments` on your view and you'll have only the comments that belongs to `current_user`. Let me know if I misunderstood your question...
j.
@j. he has comments that belongs to his posts, not his comments :) but I think it is what he wants. It is good to add `(:include => :comments)` when he loads posts.
klew
@klew: that's what I meant hehe ;]
j.
Perfect this worked. Not really sure who to award the answer to thought as it was kind of a combination of both. Thanks to everyone.
bgadoci
A: 

First, don't mess with MVC. Line:

Comment.find(:all, :order => 'created_at DESC', :limit => 3)

should be in controller:

@comments = Comment.find(:all, :order => 'created_at DESC', :limit => 3)

and in view:

<% @comments.each do |comment| %>

Or even better with partials:

<%= render :partial => "comment_item", :collection => @comments %>

It will iterate over all @comments.

Next, if you want to display all comments assigned to a post, then relation post has_many comments is enough. Use it like this:

# controller
@posts = current_user.posts(:include => :comments)

# view
<% @posts.each do |post| %>
  <%=h post.title %> - Comments: <br />
  <% post.comments.each do |comment| %>
    <%=h comment.body %>
  <% end %>
<% end %> 

If you want to show only comments posted by current_user then all your comments should have user_id field filled. And use it in the same way as you are showing users posts.

klew