Reputation: 5721
I have a Post
model which is used to store content posted by guest users, and that content is managed by an Admin user. The admin has the rights to block or unblock a particular post.
What I want to do is this:
For the first requirement, I have a model BlockedPost
which has a polymorphic association with Post
model. The post that will be blocked by the admin will be maintained in the BlockedPost
model.
For the second requirement I have to give admin the right to block or unblock any particular content. So in my posts/index.html.erb
I have done this
<% @posts.each do |post| %>
<% post.content %>
<% if post.post_blocked? %>
<td><%= link_to 'Unblock', blocked_post_path(content.id),:method => :delete%></td>
<% else %>
<td><%= link_to 'Block', create_blocked_post_path(content.id) %></td>
<% end %>
<% end %>
The post_blocked?
method above is defined in the Post model:
class Post < ActiveRecord::Base
def post_blocked?
!self.blocked_posts.nil?
end
end
This works but the problem is every time the post_blocked?
method is called it makes a database call.
Is there any way to stop this behavior and get the status of all posts in one database call itself?
Upvotes: 0
Views: 103
Reputation: 474
hmm... i think you should change your models a little, because they are unconfortable a bit and there isnt any fast way to get your posts from DB,
delete BlockedPost model
and add a column to Post model (in migration)
t.boolean :blocked, :default => true
I'd do it like this:
@blocked_posts = Post.where( :blocked => false)
@unblocked_posts = Post.where( :blocked => true )
or prepare scopes in your Post model and then in your view just display 2 lists
<% @unblocked_posts.each do |upost| %>
<%= upost.content %>
<%= link_to 'Block that post', ... %>
<% end %>
<% @blocked_posts.each do |bpost| %>
<%= bpost.content %>
<%= link_to 'Unblock', ... %>
<% end %>
Upvotes: 1