PublicActivity: Get All of User's Distinct Activities - ruby-on-rails

I'm using the Public Activity gem to track user's comments. I would like to get fetch all unique user comments in a query. I tried doing the following:
PublicActivity::Activity.where(:trackable_type=>"Comment").where(:owner_id => user.id).all.select(:trackable_id).distinct
But I'm getting the error:
ArgumentError: wrong number of arguments(1 for 0)
from (irb):14:in `select'
from (irb):14
from /Users/ttseng/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.15/lib/rails/commands/console.rb:47:in `start'
from /Users/ttseng/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.15/lib/rails/commands/console.rb:8:in `start'
from /Users/ttseng/.rvm/gems/ruby-1.9.3-p448/gems/railties-3.2.15/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Does anyone know how to extract of a user's unique activities based on trackable_id?
For reference, this is what my query results look like before I attempt to fetch the unique records:

I did following on Rails Console, see what i got
2.0.0p353 :020 > PublicActivity::Activity.where(id:1).class
=> ActiveRecord::Relation::ActiveRecord_Relation_PublicActivity_Activity
2.0.0p353 :021 > PublicActivity::Activity.all.class
=> ActiveRecord::Relation::ActiveRecord_Relation_PublicActivity_Activity
2.0.0p353 :022 > PublicActivity::Activity.where(id:1).all.class
DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`). (called from irb_binding at (irb):22)
W, [2014-09-06T01:47:09.341145 #8594] WARN -- : DEPRECATION WARNING: Relation#all is deprecated. If you want to eager-load a relation, you can call #load (e.g. `Post.where(published: true).load`). If you want to get an array of records from a relation, you can call #to_a (e.g. `Post.where(published: true).to_a`). (called from irb_binding at (irb):22)
PublicActivity::Activity Load (0.6ms) SELECT "activities".* FROM "activities" WHERE "activities"."id" = 1
D, [2014-09-06T01:47:09.343063 #8594] DEBUG -- : PublicActivity::Activity Load (0.6ms) SELECT "activities".* FROM "activities" WHERE "activities"."id" = 1
=> Array
2.0.0p353 :023 >
As you can see,u are performing select operation on an array, that's why u are get such error ArgumentError: wrong number of arguments(1 for 0)
try this instead,
PublicActivity::Activity.where(:trackable_type=>"Comment").where(:owner_id => user.id).select(:trackable_id).distinct

The answer was to run the following:
PublicActivity::Activity.where(:trackable_type=>"Comment").where(:owner_id => user.id).select("DISTINCT ON (trackable_id) *")

Related

I'm confused by Model (call 'Model.connection' to establish a connection) message received in console

I'd noticed this recently after starting my first Rails 5 app, but up until this point, it wasn't causing an issue I couldn't overcome.
The point that I couldn't overcome came when I tried to write my first Rake task. I continued to get this error:
ruby 2.3.3-p222
╳ ad_board categories ◆◆ rake reprocess_images
rake aborted!
NameError: uninitialized constant Image
/home/myname/Documents/workspace/ad_board/lib/tasks/reprocess_images.rake:3:in `block in <top (required)>'
/home/myname/.rvm/gems/ruby-2.3.3#myapp/gems/rake-11.3.0/exe/rake:27:in `<top (required)>'
/home/myname/.rvm/gems/ruby-2.3.3#myapp/bin/ruby_executable_hooks:15:in `eval'
/home/myname/.rvm/gems/ruby-2.3.3#myapp/bin/ruby_executable_hooks:15:in `<main>'
Tasks: TOP => reprocess_images
I assumed I either wrote the rake task incorrectly(could still be the case) or that I had made my model image.rb in this case images.rb, but I had not.
When I went to rails c to see if I could figure out what was going on, after typing in Image, expecting to get back Image's parameters, I instead got back this error message:
[1] pry(main)> Image
=> Image (call 'Image.connection' to establish a connection)
So, I tried a few other things:
[2] pry(main)> Image.connected?
=> false
[3] pry(main)> User.connected?
=> false
[4] pry(main)> Gallery.connected?
=> false
and...
[1] pry(main)> Image
=> Image (call 'Image.connection' to establish a connection)
[2] pry(main)> User
=> User (call 'User.connection' to establish a connection)
[3] pry(main)> User.first
User Load (1.3ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT $1 [["LIMIT", 1]]
=> #<User id: 1, email: "user#example.com", created_at: "2017-01-10 21:43:53", updated_at: "2017-01-10 21:43:53", name: "First User", role: "admin", auth_token: nil>
[4] pry(main)> Image.first
Image Load (0.9ms) SELECT "images".* FROM "images" ORDER BY "images"."id" ASC LIMIT $1 [["LIMIT", 1]]
=> #<Image:0x0000000595bf00 id: 1, file: "creativity.jpg", user_id: 20, created_at: Tue, 10 Jan 2017 21:43:58 UTC +00:00, updated_at: Tue, 10 Jan 2017 21:43:58 UTC +00:00>
I also typed in Image.connection, but all it did, like the above code, was to temporarily make a connection. As soon as I left the console I continued to get the original error message from running my rake task.
I went back into the console and typed Image, and received the message => Image (call 'Image.connection' to establish a connection)
So, the first question, is why does the "connection" break, does not establish or stay on its own? I have not run into this before now, in my limited experience.
The obvious follow-up is, how do I fix the issue and maintain a connection?
Thanks in advance for any insight into this issue you can give me.
The connection doesn't break, it just doesn't connect until you do something where it needs to. There isn't anything to fix connection wise. Your actual rake issue is that it can't find the Image model. I suspect this is because you're not telling rake to load the rails environment.
In rails you can do the following in rake
task reprocess_images: :environment do
Image.find_each do |img|
#do something
end
end
The :environment tells it to load the rails environment which will autoload things for you.
you can do
console { ActiveRecord::Base.connection }
in your development environment to ignore it.

RUBY - Couldn't find User with 'id'=1

I am currently receiving this error:
ActiveRecord::RecordNotFound in MainController#index
After I destroyed a preference, which was held by myself.
Error:
ActiveRecord::RecordNotFound in MainController#index
Couldn't find User with 'id'=1
def get_owner
return User.find( self.owner ); // LINE WITH ERROR
end
Here is post.rb:
class Post < ActiveRecord::Base
enum status: [ :ps_normal, :ps_locked, :ps_blocked, :ps_protected ]
enum sortable: [ :school, :company, :date ]
validates :owner, presence: true
def owner_name
return self.get_owner.display_name;
end
def get_owner
return User.find( self.owner );
end
def readable?
return (self.status != :blocked ) ? true : false;
end
end
UPDATE#1
2.3.0 :001 > User.find(1)
User Load (1.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 1]]
ActiveRecord::RecordNotFound: Couldn't find User with 'id'=1
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:324:in `raise_record_not_found_exception!'
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:444:in `find_one'
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:423:in `find_with_ids'
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/relation/finder_methods.rb:71:in `find'
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/querying.rb:3:in `find'
from /usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/core.rb:131:in `find'
from (irb):1
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:110:in `start'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/console.rb:9:in `start'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:68:in `console'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
from /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
How should I fix this? Add userid=1?
Update #2
I deleted my own preference under my own username and I received this error. People are saying I am missing id=1, but I am unsure on how to add it back into the database
As per your console output, there is no user with the id of 1. So if you need a user with id=1 you can do it like this.
First, create a user with the same details which you had for the deleted user. After the user successfully created then go to Rails console and:
u = User.last
# => #<User id: x, ...... >
u.update_column(:id, 1)
Please refer to Rails API doc here for more info. Choose according to the Rails version that you are using.

Unable to query hstore attribute in Rails [duplicate]

This question already has answers here:
NoMethodError when I try to acces a field of an object taken from the DB
(4 answers)
Closed 7 years ago.
I've added a hstore attribute to my model:
class ChangePerDayAverageInterestToHstore < ActiveRecord::Migration
def change
add_column :companies, :per_day_average_interest, :hstore
end
end
Now when I generate the item via the console, I am able to query it without issue. Like so:
irb(main):002:0> t = Company.new per_day_average_interest: {1 => 10, 2 => 3}
irb(main):011:0> t.per_day_average_interest
=> {"1"=>"10", "2"=>"3"}
irb(main):013:0> t.per_day_average_interest["1"] => "10"
irb(main):014:0> t.per_day_average_interest["2"]
=> "3"
When I save it, then query it, I get a No Method error:
irb(main):028:0> t.save!
(0.2ms) BEGIN SQL (0.3ms) INSERT INTO "companies" ("created_at", "per_day_average_interest", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["created_at", "2015-06-08 19:24:39.694533"], ["per_day_average_interest", "\"1\"=>\"10\",\"2\"=>\"3\""], ["updated_at", "2015-06-08 19:24:39.694533"]]
(21.4ms) COMMIT
=> true
irb(main):029:0> d = Company.where(:id => 44)
Company Load (0.5ms) SELECT "companies".* FROM "companies" WHERE "companies"."id" = 44
=> #<ActiveRecord::Relation [#<Company id: 44, name: nil, average: nil, created_at: "2015-06-08 19:24:39", updated_at: "2015-06-08 19:24:39", revenue_average: nil, country: nil, job: nil, model_name:
nil, average_daily_interest: nil, per_day_average_interest: {"1"=>"10", "2"=>"3"}>]>
irb(main):030:0> d.per_day_average_interest
NoMethodError: undefined method `per_day_average_interest' for #<Company::ActiveRecord_Relation:0x007fa16d296dd0>
from /home/action/.gem/ruby/2.1.1/gems/activerecord-4.1.0/lib/active_record/relation/delegation.rb:136:in `method_missing'
from /home/action/.gem/ruby/2.1.1/gems/activerecord-4.1.0/lib/active_record/relation/delegation.rb:99:in `method_missing'
from (irb):30
from /home/action/.gem/ruby/2.1.1/gems/railties-4.1.0/lib/rails/commands/console.rb:90:in `start'
from /home/action/.gem/ruby/2.1.1/gems/railties-4.1.0/lib/rails/commands/console.rb:9:in `start'
from /home/action/.gem/ruby/2.1.1/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:69:in `console'
from /home/action/.gem/ruby/2.1.1/gems/railties-4.1.0/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /home/action/.gem/ruby/2.1.1/gems/railties-4.1.0/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
Am I querying it the wrong way? Is there something I am missing?
Thanks!
The where statement returns the collection of objects and your column belongs to one object so you need to do the following
d = Company.where(:id => 44).first
As you can see d is ActiveRecord::Relation object, which is a wrapper of the all Company objects after filtering using where. The reader method per_day_average_interest is defined on the Company model instance, so you need to call as I have shown below.
d.first.per_day_average_interest
if you want all the values d.pluck(:per_day_average_interest).

Mysql2::Error: Unknown column 'users.*' in 'field list'

I'm seeing this error thrown for multiple tables. Searching StackOverflow it seems most peoples problems are related to a specific column missing but in my case it's trying to select everything ie. using "*".
Anyone have any insight?
Mysql2::Error: Unknown column 'users.*' in 'field list'
UPDATE
From the rails log:
Mysql2::Error: Unknown column 'users.*' in 'field list': SELECT `users`.`*` FROM `users` WHERE `users`.`id` = 53 ORDER BY `users`.`id` ASC LIMIT 1
I figured out how to reproduce this locally or at least how I think it may be occurring:
2.1.2 :037 > client = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "root", :database => "development")
=> #<Mysql2::Client:0x007ff45b72dd30 #read_timeout=nil, #query_options={:as=>:hash, :async=>false, :cast_booleans=>false, :symbolize_keys=>false, :database_timezone=>:local, :application_timezone=>nil, :cache_rows=>true, :connect_flags=>2147525125, :cast=>true, :host=>"localhost", :username=>"root", :password=>"root", :database=>"development"}>
2.1.2 :038 > result = client.query("SELECT `users`.`*` FROM `users` LIMIT 1")
Mysql2::Error: Unknown column 'users.*' in 'field list'
from (irb):40:in `query'
from (irb):40
from /Users/mark/.rvm/gems/ruby-2.1.2/gems/railties-4.1.7/lib/rails/commands/console.rb:90:in `start'
from /Users/mark/.rvm/gems/ruby-2.1.2/gems/railties-4.1.7/lib/rails/commands/console.rb:9:in `start'
from /Users/mark/.rvm/gems/ruby-2.1.2/gems/railties-4.1.7/lib/rails/commands/commands_tasks.rb:69:in `console'
from /Users/mark/.rvm/gems/ruby-2.1.2/gems/railties-4.1.7/lib/rails/commands/commands_tasks.rb:40:in `run_command!'
from /Users/mark/.rvm/gems/ruby-2.1.2/gems/railties-4.1.7/lib/rails/commands.rb:17:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
The query:
SELECT `users`.`*` FROM `users` LIMIT 1
fails when the special all selector * is wrapped in quotes.
SELECT `users`.* FROM `users` LIMIT 1
works without issue. Perhaps that is a MySQL thing? Regardless, these queries are generated by ActiveRecord / ActiveModel so perhaps I've found a bug.

Ruby on Rails Console Error

I am try on to insert a value via the Rails console into the database, but it's not working.
the first command is
u=users.create(:name=>"bob",:address=>"Dublin")
this is the output after I running the first command
u=Users.create(:name=>"Ben",:address=>"Dublin")
(0.2ms) BEGIN
SQL (0.3ms) INSERT INTO `users` (`address`, `created_at`, `email`, `name`, `password`, `updated_at`) VALUES ('Dublin', '2012-04-16 23:15:48', NULL, 'Ben', NULL, '2012-04-16 23:15:48')
(9.1ms) COMMIT
=> #<Users id: 2, name: "Ben", password: nil, email: nil, address: "Dublin", created_at: "2012-04-16 23:15:48", updated_at: "2012-04-16 23:15:48">
this is the second command
t=tweets.create(:status=>"I am a tweet from bob",:user=>u)
NameError: undefined local variable or method `tweets' for main:Object
from (irb):4
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:47:in `start'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands/console.rb:8:in `start'
from /opt/bitnami/ruby/lib/ruby/gems/1.9.1/gems/railties-3.2.1/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
Assuming you have a Tweet model, you want
u = User.first
t = Tweet.create(:status => "I am a tweet from bob", :user => u)

Resources