[ActionCable] Filter data based on params

30 views
Skip to first unread message

Stefan Buhrmester

unread,
Oct 30, 2018, 1:30:44 PM10/30/18
to Ruby on Rails: Talk
Hello all,

I've been searching a lot but wasn't able to find a solution for this (what I thought should be a really "simple" thing).

Basically, what I want to do is to create a subscription where the messages that are received by the subscriber are filtered based on the passed params.

For example, something like this:

class PeopleChannel < ApplicationCable::Channel
 # only send people that are older than params[:min_age]
  def subscribed
   stream_for Person do |person|
      person
.age > params[:min_age]
   end
 end
end

Or, what would be a kick-ass feature but probably difficult to implement, would be to stream from an active record relation, and send only the records that are included in the relation (even if they have just been created).

class PeopleChannel < ApplicationCable::Channel
 # only send things that are older than some age
  def subscribed
    peo
ple = Person.where('age > ?', params[:min_age])
   stream_for people
 end
end

Anybody got any ideas how to do this? Filtering messages seems like such a basic thing but I can't find a way.

Stefan

Stefan Buhrmester

unread,
Oct 30, 2018, 1:44:03 PM10/30/18
to Ruby on Rails: Talk
Ok, just dug into the source code and think I found a solution:

stream_from 'some_channel', coder: ActiveSupport::JSON do |person|
  transmit
(thing) if (person['age'].to_i > params[:min_age])
end

Reply all
Reply to author
Forward
0 new messages