ruby on rails - How to prevent a button appearing in index.html.erb if a condition has been met -
ok, have in articles index.html.erb
<td><%= pluralize(article.likes.count, "like") %></td> <td><%= button_to '+1', "/articles/#{article.id}/user/#{current_user.id}/like_vote", method: :post %></td> but if voter has liked article, how prevent button showing in index.html.erb? there simple way prevent button showing in index.html.erb?
this method in articlescontroller:
def like_vote @article = article.find(params[:id]) @user_id = params[:user_id] likes = like.where("user_id = ? , article_id = ?", @user_id, @article.id ) if likes.blank? @article.likes.create(user_id: current_user.id) end redirect_to(article_path) end
rails provides optimal way i.e., scope set of constraints on database interactions (such condition, limit, or offset) chainable , reusable.
add scope like model below:
class < activerecord::base scope :voted_count, ->(user_id, article_id) { where("user_id = ? , article_id = ?", user_id, article_id).count } end update view below:
<td><%= pluralize(article.likes.count, "like") %></td> <td><%= button_to('+1', "/articles/#{article.id}/user/#{current_user.id}/like_vote", method: :post) if like.voted_count(current_user.id, article.id) == 0 %></td>
Comments
Post a Comment