Ruby on Rails Voting Update

Right now, I am in the middle of creating a social media application on Ruby on Rails, I have implemented a 5-point voting system. Where you can vote for news published on the website from 1-5, I would like to know what is the best approach when processing updates in the voting system.

In the example. If the user has already voted in the article, I would like to return the account that he gave in this article and gently block the vote (since I allow only 1 vote per user, and I can change your vote at any time), but if he is not me I will give an article with a vote of 0.

I know a way to do this, I could do it in the view and check if the current user voted for this article, I would send them to the EDIT view otherwise in the SHOW view. (I think)

In any case, what would be the โ€œrightโ€ approach for this?

EDIT: I forgot to say that the voting field is partial, which I do. Is it possible to just somehow update the part?

EDIT2:

class Article < ActiveRecord::Base

  has_many :votes
  belongs_to :user

  named_scope :voted_by, lambda {|user| {:joins => :votes, :conditions => ["votes.user_id = ?",  user]}  }
end

class User < ActiveRecord::Base
  has_many :articles
  has_many :votes, :dependent => :destroy

  def can_vote_on?(article)
    Article.voted_by(current_user).include?(article) #Article.voted_by(@user).include?(article)
  end

end
+3
source share
1 answer

Create a method in the user model that responds trueif the user can vote for the article:

class User < ActiveRecord::Base

...

def can_vote_on?(article)
  articles_voted_on.include?(article) # left as an exercise for the reader...
end

end

In the view, visualize the form if the user can edit, otherwise display the normal view:

<% if @user.can_vote_on?(@article) %>
  <%= render :partial => "vote_form" %>
<% else %>
  <%= render :partial => "vote_display" %>
<% end %>

. .

EDIT2

, current_user . , , .., .

, ( ) . self current_user, User:

( )

  def can_vote_on?(article)
    Article.voted_by(self).include?(article)
  end

( )

<% if current_user.can_vote_on?(@article) %>

@user current_user, .

, , user.id, :

named_scope :voted_by, lambda {|user| {:joins => :votes, :conditions => ["votes.user_id = ?",  user.id]}  }
+1
source

Source: https://habr.com/ru/post/1763162/


All Articles