Rails 4 SQL Join Code - sql

I'm building a marketplace app. I have a Listing model (users list items to sell) and a User model. In the listing model, I have a userid column. And in the User model, I have a name field. In my listing show page, I want to display something like the below:
"Sold by #{#listing.user.name}"
But the join doesn't work in retrieving the name from the user table. If I change it to listing.userid then it works but I want to display the users name.
my user model has has_many :listings, dependent: :destroy
My listings model has belongs_to :user.
How can I display the user's name on the listing show page?

If you really have a column called userid instead of user_id then you have something very slightly different to what Rails expects... which is why Rails isn't finding it for you automatically.
Your best bet is to rename the column (using a migration) to user_id to take advantage of the Rails default behaviour. Trust me - it's worth the effort up front if you can do this.
If for some odd reason you can't (serious business constraints), then there are ways of telling rails that you are using a non-standard foreign-key... but lets not get to that unless you have to.

Related

Can't figure out how to query a 2nd level resource in Rails

I'm having trouble when querying Users.
My nesting resources are:
resources :users do
resources :photos do
resources :pins
end
end
1.) I have a user model, that has_many :photos.
2.) :photos has_many :pins
I want to list my users on which users have more pins in their photos.
So, I tried:
#members_ordered = User.includes(photos: :pins).group("users.id").group("photos.id").group("pins.id").order('COUNT(pins.id) DESC')
Not working though. Any ideas? Thanks guys
I have two observations, but neither directly fix the code in your example.
First, looking at my output from trying something similar, it seems like you either need quite complex SQL (which really isn't Rails' forte) or several simple queries (which, depending on the size of your app, could hit performance) to achieve this.
A little experimenting doesn't seem to show a significant difference (<1ms) in the time that one more complex query takes compared to that which three simple queries require (as in solution one)
Solution one, if performance is not crucial, for example, if this is a small, low-traffic solution, my instinct would be to add that the User model has_many :pins, through: :photos, which lets you call things like User.includes(photos: :pins).all, then user.pins.count, although, as I've mentioned, this causes a bit more database use.
Solution two, if performance is important, my suggestion would be to cache the count of pins against the user model. This could be as simple as an extra database column to store it, and have a background process (using delayed_job or similar) re-calculate the count each time it changes (so, maybe after_create in the Pin model.
The benefit of this is the slow, time-consuming query only gets run when the value changes, and the rest of the time, the value gets lifted from a single-table SELECT, which should take quite a bit less time than either solution one or the more complex query.
Both of these are less-than-perfect, and I think the most elegant and efficient way of working is to use a combination of a built-in function and a beautifully simple query:
The third solution, which brings together both of these options to some extent, is Rails' counter_cache option. As there are two levels to it, I can't see a native way to include all of these in one query, so we will automatically generate a count for each Photo, then add these up to get the User count.
Create a migration to add a pins_count field to the Photo model, so, in terminal, type;
rails g migration AddPinsCountToPhotos pins_count:integer
Update the belongs_to :photo line of the Pin model to;
belongs_to :photo, counter_cache: true
Now, every time a Pin gets created or deleted, the pins_count column of its Photo will be updated.
Now, to get the values for users;
Create a migration to add a pins_count field to the User model, so, in terminal, type;
rails g migration AddPinsCountToUsers pins_count:integer
Now we need to create an method in the Photo model, which we will run each time a pin is saved, so add this to your Photo model;
def update_user_counts
total_photos = self.user.photos.sum(:pins_count)
self.user.update_attribute(:pins_count, total_photos)
end
Finally, we need to tell Rails to call this whenever a pin is created or updated. We do this with a simple method that just calls the action from the Photo model;
after_save :update_photo_counts
def update_photo_counts
photo.update_user_counts
end
Now, whenever a pin is saved, it automatically updates the Photos pins_count, and then our new method totals the pins_counts from all of the Photos for that user, and saves them to the Users pins_count

Rails - How to order multiple associations?

I want to enable users of my app to create online polls which have an arbitrary amount of questions. Questions come in two flavours: multiple choice and open ended
My idea is to build something like this:
Poll
has_many open_question
has_many multichoice_questions
With apropriate belongs_to in the associated models.
How do i make it possible to save the order in which questions appear, so that it can be recreated when the poll is taken?
I'm thinking about serializing an ordered 3D array with question id's and types, but that feels wrong (it's saving the same information twice).
What would be a Rails way to model this?
If it were me I would set up my model like this:
User has_many Polls has_many OpenQuestions && MultichoiceQuestions
Then I could do something like this:
#user = current_user
#poll = #user.polls.find(params[:poll_id])
#open_questions = #poll.open_questions.order('created_at ASC')
Alternatively, if you feel you need even more control you could leverage some scopes.
http://guides.rubyonrails.org/active_record_querying.html#scopes

Joining a "has many through" association using ActiveRecord

Working with Exported Data from API
I'm building a leaderboard that displays the Team.name of each team as well as the users who have picked that particular team as their favorites. I'm also populating another attribute Favorite.points; to display the users with the most points accumulated for that respective team.
Here are the models I'm working with:
Favorite.rb
class Favorite < ActiveRecord::Base
belongs_to :users
belongs_to :teams
end
Team.rb
class Team < ActiveRecord::Base
has_many :favorites
has_many :users, :through => :favorites
end
User.rb
class User < ActiveRecord::Base
has_many :favorites
has_many :teams, :through => :favorites
end
To start this process, I'm trying to match up the id's that are common between Team.external_id and Favorite.team_id (the same is the case for User.external_id => Favorites.user_id). I can use Team.find_all_by_external_id(3333) to get the IDs of all Team objects that have an external_id of '3333'and the same goes for Favorite.find_all_by_team_id.
What's the next best step for me to obtain/show the data I'm looking for? Is a SQL join clause best? Or is it better to write if statements matching up values and iterating through the JSON arrays?
Any help is appreciated, thanks!
This will get you all the favorites whose team_id matches the external_id attribute of a row in the teams table, for a specific team (here, the team with id 3333):
Favorite.joins("left outer join teams on teams.external_id = favorites.team_id")\
.where('team_id' => 3333)
The tricky thing here, as I mentioned in my comments, is that you are going entirely against the grain of rails associations when you match the external id on the Team model (an attribute which you have created) to the team_id on the Favorite model (which is used throughout rails to get and assign associations).
You will see the problem as soon as you try to actually get the team for the favorite you find in the above join:
f = Favorite.joins("left outer join teams on teams.external_id = favorites.team_id")\
.where('team_id' => 3333).first
=> #<Favorite id: 1, user_id: nil, team_id: 3333, points: nil, created_at: ... >
f.team
Team Load (0.3ms) SELECT "teams".* FROM "teams" WHERE "teams"."id" = 3333 LIMIT 1
=> nil
What's going on here? If you look closely at the query, you'll see that rails is selecting teams whose id is 3333. Note that it is not looking for teams whose external id is 3333, which is what you want.
The fundamental problem is that you are trying to use external ids (ids specific to your API) for associations, which won't work. And indeed, there is no reason to do it this way.
Instead, try this:
Favorite.joins(:team).where('teams.external_id = 3333')
This will get you all favorites whose teams have the external id 3333. Note that Rails will do this by joining on teams.id = favorites.team_id, then filtering by teams.external_id:
SELECT "favorites".* FROM "favorites" INNER JOIN "teams"
ON "teams"."id" = "favorites"."team_id" WHERE (teams.external_id = 3333)
You can do the same thing the other way around:
Team.joins(:favorites).where('teams.external_id = 3333')
which will generate the SQL:
SELECT "teams".* FROM "teams" INNER JOIN "favorites"
ON "favorites"."team_id" = "teams"."id" WHERE (teams.external_id = 3333)
Note again that it is the id that is being used in the join, not the external id. This is the right way to do this: use the conventional id for your associations, and then just filter wherever necessary by your (custom-defined, API-specific) external id.
Hope that helps!
UPDATE:
From the comments, it seems that the team_id on your Favorite model is being defined from the API data, which means that the id corresponds to the external_id of your Team model. This is a bad idea: in rails, the foreign key <model name>_id (team_id, user_id, etc.) has a specific meaning: the id is understood to map to the id field of the corresponding associated model (Team).
To get your associations to work, you need to use ids (not external ids) for associations everywhere (with your User model as well). To do this, you need to translate associations defined in the API to ids in the rails app. When you add a favorite from the API, find the Team id corresponding to the API team id.
external_team_id = ... # get external team id from API JSON data
favorite.team_id = Team.find_by_external_id(external_team_id).id
So you are assigning the id of the team with a given external id. You need to query the DB for each favorite you load from the API, which is potentially costly performance-wise, but since you only do it once it's not a big deal.

Correct Association Between Models in Rails 3

I have a Record model and I want to create a Field model such that a given Record has_many Fields. Similarly I want each field to be associated with a Tag such that each Field has_one Tag. But each Tag can be reused many times between Field objects.
In this case would I just say that a Tag belongs_to_many Fields? Likewise would it be right to say that the Field belongs_to_many Records?
(Ultimately I want the Record object to be a container for multiple Fields. I envision having a form where I can dynamically add new Field and Tag, so that a Record might look like:
Record 1
Tag 1
Field 1
Tag 2
Field 2
...
where each Tag can either be pulled from a pre-existing pool or created on the fly) Thanks for the help!
First, I would highly recommend reading RoR Guide on Associations:
http://guides.rubyonrails.org/association_basics.html
Whether you are new or need a touch up on using Associations in RoR, read that guide.
Your question seems to be more of a logic question, but I'll start with the
code for it:
class Record < ActiveRecord::Base
has_and_belongs_to_many :fields
...
class Field < ActiveRecord:Base
has_and_belongs_to_many :records
belongs_to :tag
...
class Tag < ActiveRecord:Base
has_many :fields
...
Each Record connects to many different fields, and each field connects to many different Records. This is a classic example of a many to many association. The logic in your code when you actually use these models is what will make the Record Model seem like a container (Because technically you could say a Field is a container for many records).
Each Field will have 1 Tag associated with it, but that same Tag could be used with any number of fields (You could say the Fields are reusing the tags). This is a one to many association. When making this connection you would use belongs_to in the Field model, and has_many in the Tag model.
Since Tag is connected to the Field Model, the logic you are looking for: A Record is a container for Fields and Tags, makes sense with this setup.
Here is a simple example of fetching a Tag inside a record:
#Returns the Tag Associated with the first field
#"inside" the first Record in the database.
Record.first.fields.first.tag
Likewise, one could easily go the opposite direction:
Tag.first.fields.first.records.first
Make sure to leverage the Rails commands via command line to quickly setup your migrations and models. As far as options on how you want your associations to handle things when one as deleted, saved, and so on, just read the guide at the top to find what you are looking for.

Rails ActiveRecord: How to select all users with a given permission?

I've got a model called Users, some of whom are considered Authors. This is accomplished through a table called Roles, which lists a number of different roles: "Author" is one. A many-to-many association in a table called Permissions links Roles and Users.
To check whether a User has the Author permission, I have a method that runs through the Permissions linked to that particular User and returns whether any of them also links to the Author permission.
This system has served me well. However, it makes it clunky to search and order the Authors on the site. What I'd like to do is something simple and graceful, ideally like a named scope that will allow me to say things like Users.authors.order("date_joined") or something like that.
As it is right now, I don't have any way to get the group of "Author" users other than pulling all Users out of the database, running through them one at a time, searching for their Author permission, and then adding them to an array of Users if it is found.
This seems rather ungraceful, especially as I have to do it every time I want to present the list of Authors in a view.
Is there a better way?
EDIT -- Solution:
Following the helpful advice below and the tips from http://railscasts.com/episodes/215-advanced-queries-in-rails-3?view=asciicast I was able to put together the following.
In User.rb:
class User < ActiveRecord::Base
scope :authors, joins(:permissions) & Permission.author_permissions
scope :admins, joins(:permissions) & Permission.admin_permissions
In Permission.rb:
class Permission < ActiveRecord::Base
scope :author_permissions, where("role_id = ?", Role.find_by_rolename("author"))
scope :admin_permissions, where("role_id = ?", Role.find_by_rolename("administrator"))
And voila! Now I can call Users.authors and it works like a charm.
Keep the schema structure that you have but make sure to add the proper table indexes.
Then to query for users in specific roles you can do
User.all(:joins => :roles,
:conditions => {:roles => {:id => pick_a_role_id}})
have you looked at CanCan? It will probably require a little refactoring, mostly to create a current_user method. A guide to roles can be found here