Use the Ruby selection method with respect to Rails and update it.

I have an ActiveRecord user relationship to previous "voices" ...

@previous_votes = current_user.votes

I need to filter them to votes only by the current “call”, so the Ruby method selectseemed to be the best way to do this ...

@previous_votes = current_user.votes.select { |v| v.entry.challenge_id == Entry.find(params[:entry_id]).challenge_id }

But I also need to update the attributes of these records, and the method selectwill turn my relationship into an array that cannot be updated or saved!

@previous_votes.update_all :ignore => false
# ...
# undefined method `update_all' for #<Array:0x007fed7949a0c0>

How can I filter my relationships, as the select method does, but not lose the ability to update / save it with ActiveRecord?

Google-like seems to named_scopeappear in all answers to similar questions, but I can’t understand that they can specifically accomplish what I need.

+5
4

, select SQL. Ruby. :

votes = Vote.scoped
votes.select{ |v| v.active? }
# SQL: select * from votes
# Ruby: all.select{ |v| v.active? }

update_all - SQL, Ruby. Ruby SQL.

votes = Vote.scoped
votes.select{ |v| v.active? }
# N SQL operations (N - number of votes)
votes.each{ |vote| vote.update_attribute :ignore, false }
# or in 1 SQL operation
Vote.where(id: votes.map(&:id)).update_all(ignore: false)

, SQL:

Vote.where(active: true).update_all(ignore: false)

select, SQL. Rails, :

entry = Entry.find(params[:entry_id])
current_user.votes.joins(:challenges).merge(entry.challenge.votes)
# requires following associations:
# Challenge.has_many :votes
# User.has_many :votes
# Vote.has_many :challenges

Rails SQL. SQL , - .

+2

, - :

@entry = Entry.find(params[:entry_id])    
@previous_votes = Vote.joins(:entry).where(entries: { id: @entry.id, challenge_id: @entry.challenge_id })
+2

scopes. :

class Vote < ActiveRecord::Base
  scope :for_challenge, lambda do |challenge_id|
    joins(:entry).where("entry.challenge_id = ?", challenge_id)
  end
end

:

challenge_id = Entry.find(params[:entry_id]).challenge_id
@previous_votes = current_user.votes.for_challenge(challenge_id)
+2

collection_select select. collection_select select, ActiveRecord, , , select.

@previous_votes = current_user.votes.collection_select { |v| v.entry.challenge_id == Entry.find(params[:entry_id]).challenge_id }

@previous_votes

EDIT: AR

@previous_votes = current_user.votes.collect {|v| records.detect { v.entry.challenge_id == Entry.find(params[:entry_id]).challenge_id}}
0

All Articles