ActiveRecord associations, has_many_through - ruby-on-rails-3

I've been trying to wrap my head around these associations and I've run into a bit of a snag. The app I'm working on has 2 models at the moment: Ingredient, and Recipe. The logic behind each is as follows:
The Ingredient model contains info on food items, such as name, bulk price, etc.
The Recipe model contains the name of the recipe, preparation instruction, and a list of ingredients (along with the amount required for the recipe).
After digging through some of the questions on here, and watching a few railscasts I've determined that a has_many_through relationship may be better for what I'm attempting to do, since I'd like to include additional info about the ingredient in the recipe (amount required).
Based on my limited experience in this area, I'd like to approach it like this:
class Recipe < ActiveRecord::Base
has_many :ingredients_recipes
has_many :ingredients, :through => :ingredients_recipes
end
class Ingredient_Recipe < ActiveRecord::Base
belongs_to :ingredient
belongs_to :recipe
end
class Ingredient < ActiveRecord::Base
has_many :ingredients_recipes
has_many :recipes, :through => :ingredients_recipes
end
Where the ingredients_recipes table would have fields similar to this: recipe_id, ingredient_id, ingredient_qty (for storing how much of a particular ingredient is in a recipe)
Is this the proper way to approach it code-wise, based on the functionality I mentioned above? Any help would be greatly appreciated. Thanks!
Edit
I'd also like to be able to add these new ingredients to the recipe from the recipe form. Would this require anything extra, like having to do accepts_nested_attributes_for the through table, or is this something that Rails would handle on it's own?

The :has_many through approach works best when one object can have zero or many other objects connected & there are some properties associated with each connection.
For example, in your case, you'd be storing the amount of each ingredient along with the recipe_id an ingredient_id in the Connections table.
So, it looks GOOD to me. :)
However, you should consider naming your Ingredient_Recipe table to something more appropriate.

Related

Rails Postgres hstore or jsonb to store many to many relations

There is a table 'Products' with columns (id, tile, price, description, shop_id, timestamps)
Column price and shop_id are dynamic. The rest of column are static.
Also there is a table 'Shops' with columns (id, name, timestamps).
Shop has many products. Product can migrate among all shops and products.shop_id can be blank.
I want to have history about which products a shop had. For example, yesterday shop had products and their prices. Day before yesterday shop had other products and/or other their prices. So I want to have something like
'ShopHistory' (id, data, date, timestamps), where data is hstore or json. So it should have hash like { key: value}, where key is id of product and value is its current price. But I would like to joins data column with products in order to know about title and description of products. I have no idea how to do that.
It looks like ShopHistory is a join table between shop and products, but all information are stored in one row.
Could we help me? Maybe anyone knows a better way to implement all of this. Any thought and articles are welcome.
Thanks!
P.S. I use rails(ActiveRecord) and PostgreSQL, but answers from guys who know only Postgres are good for me too.
I get your intent, but frankly I don't think it's going to work out for you in a straightforward, easy way. (As a rule of thumb, in ruby and in rails, if it isn't straightforward, you're probably not doing it the ruby/rails way).
Why do I know this? Because I tried before to do a very similar thing to what you want to do with an hstore, with no luck:
Can I use ActiveRecord relationships with fields from an Hstore?
As a better solution (what worked out for me in the end), please consider making an intermediate model to match Shops to Products, (maybe you'll want to name this intermediate model something like Shop_product, with a join table shops_products, but the name is up to you) then join both models using the intermediate model with a has_many through: relationship as detailed here:
http://edgeguides.rubyonrails.org/association_basics.html#the-has-many-through-association
Something like:
class Shop << ActiveRecord::Base
has_many :shop_products
has_many :products, through: :shop_products
end
class ShopProduct << ActiveRecord::Base
belongs_to :shop
belongs_to :product
end
class Product << ActiveRecord::Base
has_many :shop_products
has_many :shops, through: :products
(There's more info about how to create all of that in the link, I recommend that read)
Now you will have an association set up, so you can get:
Shop.find_by_id(1).products
Product.find_by_id(1).shops
Finally, I think you can use ActiveRecord scopes to solve the second computational problem that you need to solve (that is, find the price per day in the past).
Scopes will allow you, ideally, to do queries like:
Shop.products.active_yesterday
class Product << ActiveRecord::Base
scope active_yesterday -> { where('updated_at BETWEEN ? AND ?', 1.day.ago.beginning_of_day, 1.day.ago.end_of_day) }
has_many :shop_products
has_many :shops, through: :shop_products
end
All of my code is not production-ready and not tested, but I think my examples and links should be enough to get you on the right path.
Let me know if you need more help and I can try to help.

HABTM associations in Rails : collecting and counting the categories of a model's children

I have a has_and_belongs_to_many relationship setup. It looks like this:
books have_and_belong_to_many categories
categories have_and_belongs_to_many books
a store has_many books
a book belongs_to a store
I'm trying to show how many books in each store belong to each category. So my view would show Store X has 200 books and 80 of them are mystery, 60 are non fiction, etc.
I have been trying out a bunch of different ways of doing this, but no success so far. I think I'm starting in the wrong place. Any direction would be much appreciated.
Thanks
This is Rails 4 and psql by the way.
Provided that you have a books_categories join table you can add a has_many :categories, through: :books association to which links stores and categories through books.
class Store < ActiveRecord::Base
has_many :books
has_many :categories, through: :books
end
That's the easy part. Now lets get each category and the books count (revised):
def books_per_category
categories.select('categories.id, categories.name, count(books.id) as count')
.group('categories.id, categories.name')
.map do |c|
{
name: c.name,
count: c.count
}
end
end
Courtesy of #jakub-kosiƄski
Generally, instead of using Rails' built-in 'has_and_belongs_to_many' method, it is better practice to use a join table. In this setup, you have three tables:
Books
Categories
BookCategories
The BookCategories (or whatever you decide to call it) is a join table that belongs_to both Books and Categories and has a Foreign ID of each. You would then use Rails' "has_many :through" to link the Books and Categories.
The store would have a 'has_many' relationship with books. With the prior relationship setup right, you can then use this method to get the count for a store for a particular category:
Store.books.where(category:'Mystery')

Preloading using includes on unrelated models

Suppose I have three models, set up something like this:
class Student < ActiveRecord::Base
has_many :tests
has_many :cars
end
class Car < ActiveRecord::Base
belongs_to :student
end
class Test < ActiveRecord::Base
belongs_to :student
end
I want to query all tests whose student does not have car. Preloaded.
I've tried the following:
Test.includes(:cars) # does not work because the two are not associated
Test.joins('inner join cars ON tests.student_id = cars.student_id') # works, but it doesn't preload the Cars model in my result
I'd prefer not to create a has_many :through relationship, because they really aren't related at all, but I'm not opposed to it if that's the best solution.
Thoughts?
Rails 4.1.5
PostgreSQL 9.3.4
ruby 2.1.2
A join across three tables is an inefficient way to do this. Rails might even be smart enough to realise this and split it into seperate db queries.
I would do it like this, which has two simple queries instead
student_ids_with_car = Car.select("student_id").distinct
#tests = Test.where("student_id not in (?)", student_ids_with_car)
You don't have to use has_many :through to associations and associations of those associations at the same time.
Test.includes(:student => :cars)
Will include student's and their cars (by default it will preload, you can force a joins based include by using eager_load instead of preload).

Crafting the most efficient Rails 3 has_many :through query

I have two Rails 3 models, Product and Room defined per below. Each Room can have multiple products, and each Product can be in multiple rooms:
class Product < ActiveRecord::Base
#...
has_many :rooms, :through => :product_selection
has_many :product_selection
end
class Room < ActiveRecord::Base
#...
has_many :products, :through => :product_selection
has_many :product_selection
end
class ProductSelection < ActiveRecord::Base
#...
belongs_to :product
belongs_to :room
end
I'd like to create a query within rooms_controller.rb to return records for the first 10 rooms, and for each Room include a count of the number of products pushed to that room (to find out how many products are in each Room) and a sum of a column within Product called cost for all products in the Room (to get the total cost of all the products in the room). After calling the query, I would ideally be able to call #rooms[i].total_products and #rooms[i].total_cost (or something similar) along with the Room fields so it can be easily digested and iterated by a template.
I know I could create 10 different calls then loop through each as #room.products.count and #room.products.sum(cost), but there has to be a more efficient way...and I have a feeling I'm overlooking something obvious.
Thanks!!
The naive implementation will have you do N+1 queries...
If your desire was to just count your products efficiently, I would suggest implementing a :counter_cache
Though as you also want to perform a calculation (summation on cost), eager loading the products with the rooms query will be more desirable. The idea being to return your list of rooms and their products.
room_array = Room.includes(:products).limit(10)
If there was the further desire to make this efficient, you may want to have the database do the summation, too.

Multiple Foreign Keys for a Single Record in Rails 3?

I am working on an app that will manage students enrolled in a course. The app will have users who can log in and manipulate students. Users can also comment on students. So three of our main classes are Student, User, and Comment. The problem is that I need to associate individual comments with both of the other models: User and Student. So I've started with some basic code like this...
class Student < ActiveRecord::Base
has_many :comments
end
class User < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :student
belongs_to :user
attr_accessible :comment
end
So in the comments table, a single record would have the following fields:
id
comment
student_id
user_id
created_at
updated_at
This presents several problems. First, the nice Rails syntax for creating associated objects breaks down. If I want to make a new comment, I have to choose between the foreign keys. So...
User.comments.create(attributes={})
OR
Student.comments.create(attributes={})
Another option is to arbitrarily pick one of the foreign keys, and manually add it to the attrs hash. So...
User.comments.create(:comment => "Lorem ipsum", :student_id => 1)
The problem with this option is that I have to list student_id under attr_accessible in my Comment model. But my understanding is that this poses a security risk since someone could technically come along and reassociate the comment with a different student using mass assignment.
This leads to a further question about data modeling in general using Rails. The app I'm currently building in Rails is one that I originally wrote in PHP/MySQL a few years ago. When I first studied SQL, great importance was placed on the idea of normalization. So, for example, if you have a contacts table which stores names and addresses, you would use a lot of foreign key relationships to avoid repeating data. If you have a state column, you wouldn't want to list the states directly. Otherwise you could potentially have thousands of rows that all contain string values like "Texas." Much better to have a separate states table and associate it with your contacts table using foreign key relationships. My understanding of good SQL theory was that any values which could be repeating should be separated into their own tables. Of course, in order to fully normalize the database, you would likely end up with quite a few foreign keys in the contacts table. (state_id, gender_id, etc.)
So how does one go about this in "the Rails way"?
For clarification (sorry, I know this is getting long) I have considered two other common approaches: "has_many :through =>" and polymorphic associations. As best I can tell, neither solves the above stated problem. Here's why:
"has_many :through =>" works fine in a case like a blog. So we have Comment, Article, and User models. Users have many Comments through Articles. (Such an example appears in Beginning Rails 3 from Apress. Great book, by the way.) The problem is that for this to work (if I'm not mistaken) each article has to belong to a specific user. In my case (where my Student model is here analogous to Article) no single user owns a student. So I can't say that a User has many comments through Students. There could be multiple users commenting on the same student.
Lastly, we have polymorphic associations. This works great for multiple foreign keys assuming that no one record needs to belong to more than one foreign class. In RailsCasts episode #154, Ryan Bates gives an example where comments could belong to articles OR photos OR events. But what if a single comment needs to belong more than one?
So in summary, I can make my User, Student, Comment scenario work by manually assigning one or both foreign keys, but this does not solve the issue of attr_accessible.
Thanks in advance for any advice!
I had your EXACT question when I started with rails. How to set two associations neatly in the create method while ensuring the association_ids are protected.
Wukerplank is right - you can't set the second association through mass assignment, but you can still assign the association_id directly in a new line.
This type of association assignment is very common and is littered throughout my code, since there are many situations where one object has more than one association.
Also, to be clear: Polymorphic associations and has_many :through will not solve your situation at all. You have two separate associations (the 'owner' of a comment and the 'subject' of a comment) - they can't be rationalised into one.
EDIT: Here's how you should do it:
#student = Student.find_by_id(params[:id])
#comment = #student.comments.build(params[:comment]) #First association is set here
#comment.user = current_user #Second association is set here
if #comment.save
# ...
else
# ...
end
By using the Object.associations.build, Rails automatically creates a new 'association' object and associates it with Object when you save it.
I think polymorphic association is the way to go. I'd recommend using a plugin instead of "rolling your own". I had great results with ActsAsCommentable (on Github).
As for your attr_accessible problem: You are right, it's more secure to do this. But it doesn't inhibit what you are trying to do.
I assume that you have something that holds the current user, in my example current_user
#student = Student.find(params[:id])
#comment = Comment.new(params[:comment]) # <= mass assignment
#comment.student = #student # <= no mass assignment
#comment.user = current_user # <= no mass assignment
if #comment.save
# ...
else
# ...
end
The attr_accessible protects you from somebody sneaking a params[:comment][:student_id] in, but it won't prevent the attribute from being set another way.
You still can get all comments of your users through the has_many :comments association, but you can also display who commented on a student thanks to the belongs_to :user association:
<h1><%= #student.name %></h1>
<h2>Comments</h2>
<%- #student.comments.each do |comment| -%>
<p><%= comment.text %><br />
by <%= comment.user.name %></p>
<%- end -%>
PLUS:
Don't over engineer your app. Having a state:string field is perfectly fine unless you want to do something meaningful with a State object, like storing all districts and counties. But if all you need to know a students state, a text field is perfectly fine. This is also true for gender and such.
Well, for the first part. If I understood your question correctly, I think, that since comments are listed within students controller, you should associate them through Student model (it just seems logical to me). However, to protect it from assigning wrong user id, you could do something like this
#student = Student.find params[:id]
#student.comments.create :user => current_user
current_user might be a helper that does User.find session[:user_id] or something like that.
has_many :through association doesn't make sense here. You could use it to associate User and Student through Comment, but not User and Comment through Student
Hope that helps.