rails-4 not getting all columns from 2 tables with join - ruby-on-rails

This is my model.rb
model.rb
class Compute
belongs_to :user
end
class User
has_many :computes
end
I have used this query to get all details
User.joins(:computes).where.not(skey: 'NULL')
and i got all from USER table,also i need to get one or more column
from COMPUTE with USER.

You can use like this
User.joins(:computes).where.not(skey: 'NULL').select("users.id, computes.name")

Instead of .select use .pluck. Like
Table_1.joins(:table_2).where(:conditions).pluck('table_1.col_1', 'table_1.col_2', 'table_2.col_1', 'table_2.col_2')
User.joins(:computes).where.not(skey: 'NULL').pluck('users.id', 'computes.name')

Related

Ruby On Rails + PostgreSQL: How to get all records from table A that don't have association in table B?

I have these two models:
class ModelA < ApplicationRecord
has_one :model_b
end
class ModelB < ApplicationRecord
belongs_to :model_a
end
And I need to get all records from the table model_a which don't have a matching record in table model_b - whether through an AR or a raw PostgreSQL query.
What's the most elegant/efficient way to do that?
I can think of only looping through model_a and searching for a matching record in model_b.
Thank you in advance.
Have you tried a LEFT JOIN? Something like
ModelA.left_joins(:model_b).where(table_model_b: {model_a_id: nil})
If I got your thought correctly, you can try just exclude ids with relation
ModelA.where.not(id: ModelB.pluck(:model_a_id).uniq)
For ease of understanding:
model_b_ids = ModelB.all.pluck(:id)
ModelA.where('model_b_id NOT IN (?)', model_b_ids)
You have to try left join and filter on A_id in table b.
ModelA.left_joins(:ModelB).where("model_B.model_a_id": nil)
ModelA.left_joins(:ModelB).where(model_B: { model_a_id: nil })

Print attribute of object

I have 2 classes with:
class User < ApplicationRecord
has_one :address
end
class Address < ApplicationRecord
belongs_to :user
I need to write code, which will print the value of attribute with the name 'postcode' of 100 users from database.
I have some code on this point, but not sure that it's a good way to solve the problem:
#users = User.all
#users.limit(100).each do |user|
puts "#{user.postcode}"
end
Who has better ideas?
I'd use pluck
puts User.limit(100).pluck('postcode')
# or
puts User.joins(:address).limit(100).pluck('addresses.postcode')
Pluck is best suited for your scenario.
User.where(condition).pluck(:postcode)
(#where condition is optional)
Event if you want to fetch other column with postcode you can simply include that in pluck. for e.g.
User.where(condition).pluck(:id, :postcode)
(#using multiple column inside pluck will only work with rails4 and above)

How to use raw sql to extract values from a JOIN TABLE in Rails

I've two tables users and places, joined by places_users.
I want to retrieve the last 5 places_users.
I'm trying:
Place.select("* from places_users")
but that's generating:
SELECT * from places_users FROM "places"
Do I need to use ActiveRecord directly? Or something else...
Using instances of the models would not be appropriate, as that will give me just a users' places, or all the users that have selected a place.
Thanks for your help in advance.
you could try something like:
PlaceUser.includes(:place, :user).last(10)
which should give last 10 records from PlaceUser table with related places and users
if you don't have joined table you could create it:
class PlaceUser < ActiveRecord::Base
belongs_to :user
belongs_to :place
end

Scoping a class method to current_user

I'm working on implementing a tagging system and I'm having problem querying for tagged objects with a scope.
For example, I would like to find all the user's items with a certain tag. With a class method I can currently find all the objects:
def self.tagged_with(name)
Tag.find_by_name(name).items
end
However, this has a problem. If I were to do something like: current_user.items.tagged_with(name) won't this existing method return ALL the items and not just items owned by the current_user? I suppose this is a simply querying issue but I can't figure out how to change a class method into something called on a collection. I have tried going the opposite way, to get a the collection through the tags, something like... tag.items.where(:user_id => current_user.id) but in this case, it's a many-to-many relationship and I haven't been able to get on thumb on this either.
What's the proper way to restrict a query like this?
Create an association on your User class that points to your Tag class.
class User < ActiveRecord::Base
has_many :tags
end
Then you can do:
current_user.tags.where(...)
If you don't already have an association in place, you'll need to create a migration to have the tags table reference your users table with a foreign key.
I think this will help you:
class Account < ActiveRecord::Base
has_many :people do
def find_or_create_by_name(name)
first_name, last_name = name.split(" ", 2)
find_or_create_by_first_name_and_last_name(first_name, last_name)
end
end
end
person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson")
person.first_name # => "David"
person.last_name # => "Heinemeier Hansson"
So, basically you can define your method tagged_with directly into the association!
This example is took from the documentations ActiveRecord::Associations

Can I get the table, column and type information from a model?

I'm using ruby and activerecord to get information about a mysql table.
I was hoping I could get this information directly from my model class, is this possible?
Say I have my model:
class Product < ActiveRecord::Base
end
Is it now possible for me to get information regarding:
1. mysql table
2. columns
3. column types
Or do I have to look somewhere deeper into the ActiveRecord module to get this?
Product.table_name
Product.column_names
Product.columns_hash['title'].type
Have a look at ActiveRecord::ModelSchema::ClassMethods:
class Product < ActiveRecord::Base
self.table_name # 1
self.columns # 2
self.columns_hash['name'].type # 3
end

Resources