开发者

rails3 model question

i moved from php to rails3, and i still think it was a good decision! Anyway I have some models:

users
questions
answers
question_id
votes
user_id
answer_id

model for users:

has_many :questions
has_many :votes

model for questions:

belongs_to :user
has_many :answers, :dependen开发者_开发技巧t => :destroy
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:text].blank? }, :allow_destroy => true

model for answers:

belongs_to :question
has_many :users, :through => :votes, :dependent => :destroy
has_many :votes

model for votes:

belongs_to :answer
belongs_to :user

Now my question, once a user has voted on an answer, the voting for that user and for that specific question should be closed...

I use devise and cancan for users and authorization in the rest of my project...

In my view it should look something like:

<% unless current_user.question_answered.include? question %>

and then do the script where i render the vote buttons...

In my votes model i have an answer_id and a user_id, i know the current_user.id and the current question.id so if the vote.user_id has the vote.answer_id that is in the current question.id than it shouldn't render my button making script... aarghh but how to put this to work...?

Thanks very much in advance! And best regards, Thijs


I would personally go outside of devise and write my own method. I think it's a little cleaner and easier to understand. You'll also guarantee with this method that you are only performing a single fast query to your DB. By asking current_user.questions_answered you are querying the database for all questions that a user has answered, which is potentially a much larger result set than checking if the user has voted on the current question:

class User
  def can_vote_on? question
    !question.answers.joins(:votes).where('votes.user_id = ?', id).exists?
  end
end

You can then adjust your view to:

<% if current_user.can_vote_on?(question) %>


in ability write something like this

can :vote, Answer, :votes => { :users => user }

in your view do something like

<% if can? :vote, Answer %>

(i cant really test it right now so let me know if it works)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜