简体   繁体   中英

Rails model method with association

I created an app where users can vote to polls. I started from this tutorial and then modified it to my needs.

poll.rb:

has_many :vote_options, dependent: :destroy
has_many :votes, :through => :vote_options

vote_option.rb:

belongs_to :poll
has_many :votes, dependent: :destroy

vote.rb:

belongs_to :vote_option
belongs_to :user

user.rb

has_many :votes, dependent: :destroy
has_many :vote_options, through: :votes

A user can only vote once. To check if a user voted I have on user.rb:

def voted_for?(poll)
  vote_options.any? {|v| v.poll == poll}
end

I added then a column delegated to votes table. Now want to restrict the method voted_for only to votes for which delegated is false.

So I tried:

def voted_for?(poll)
  vote_options.where(:delegated => 0).any? {|v| v.poll == poll}
end

which returns:

Mysql2::Error: Unknown column 'vote_options.delegated' in 'where clause': SELECT vote_options .* FROM vote_options INNER JOIN votes ON vote_options . id = votes . vote_option_id WHERE votes . user_id = 4 AND vote_options . delegated = 0

so I tried:

def voted_for?(poll)
  vote_options.votes.where(:delegated => 0).any? {|v| v.poll == poll}
end

which returns:

undefined method `vote' for VoteOption::ActiveRecord_Associations_CollectionProxy:0x007f002ad28be8>

Which I don't understand as I have the association in place.

What am I doing wrong? How can I fix?

If you follow completely this tutorial which is you mentioned in your post then it will be

def voted_for?(poll)
    votes.any? {|v| v.vote_option.poll == poll}
end

See this existing repo

You misunderstood associations

currently you are calling vote_options.votes , that's wrong practically.

as vote_options return collections of records, and you can't call .votes for collection it will works with single record as associations is vote_option has many votes, it means one to many not many to many.

for your case you can try

def voted_for?(poll)
  votes.where(:delegated => 0).any? {|v| v.poll == poll}
end 

if you still have any confusion go through this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM