I have a rather complicated (to me) statements to write in Rails. Under the show.html.erb of my Person.rb which is a user’s profile. Each post has a status column in database with values draft or published.
<% if @posts.blank? %>
No post.
<% else %>
<% if @person == current_user %>
<% @posts.each do |post| %>
Post title... (where all published and draft posts are shown)
<% end %>
<% else %>
<% @posts.each do |post| %>
<% if post.status == "published" %>
Post title (where only published posts are shown, draft posts are hide from other users)
<% end %>
<% end %>
<% end %>
<% end %>
Here’s the problem. Suppose User A has 1 published post and 1 draft post, it works fine; but if User B has 2 draft posts, by right no post will be shown to other users, but I want it to show No post like the first 2 lines code.
I tried named_scope in my Post.rb guided here, but when I apply .published it just returned me a non-defined error.
Please teach me how to accomplish this. Thank you very much.
I would do the following:
Create a scope for status on posts.
class Post named_scope :by_status, lambda { |status| {:conditions => {:status => status} } } endMove some logic into your controller:
class PostsController def index @person = Person.find(params[:person_id]) if current_user == @person @posts = @person.posts else @posts = @person.posts.by_status('published') end end endWrite your view:
<% if @posts.empty? %> No posts code <% else %> <% @posts.each do |post| %> Post title... <% end %> <% end %>This solution should DRY up your code and move more logic into your model.