I'm a newbie on rails. How to query for a non related model field. Say I've a billing model where I need to fetch the product group while I store only product_code in the billing model. I'm using acts as api. I need to send all product_codes along with product group which is not at all related to billing model.
Thank You
Sai
Consider,
Billing.each do |r|
product = Product.find(r.billing_item)
product_group = product.product_group
end
Of course product_group above would be an AR association, you'd need to grab whatever appropriate attribute of your ProductGroup, i.e. name or title for example.
Related
I'm on a project with Rails, Postgresql and Active Record, where I have Users, that can be either Influencers, or Creators.
The Users have common columns such as email, password, first_name and last_name, but :
influencers will have followers, eg_rate, account columns
creators will have SIRET_number and specialty columns
How can I design my database so Influencers and Creators are kind of "child" of the Users table ? I mean, is it possible to have a db where I can access a User' followers or a User's specialty with one query, or I'll always have to do multiple queries to achieve this ? I've tried to create three tables for each, with a foreign key user_id in Influencers table and Creators table. I also tried to add a user_type column to my User table where I pass the values of either "influencer" or "creator", but I'm kind of lost on how to link every tables...
Thank you everyone.
Your approach is right.
You can create a table users with the common columns and add a foreign key to influencers and creators tables.
Then when you need to retrieve the data, you can use ActiveRecord relations to easily fetch data and use ActiveRecord's includes method for relations.
For example:
class Creator < ActiveRecord::Base
# The relation must be set
has_one :user
end
# To fetch data anywhere else:
Creator.find_by(SIRET_number: 1234).includes(:user)
If you need to retrieve a creator or influencer by an attribute from related users table, you can use joins:
Creator.joins(:users).where(users: {email: "foo#bar.com"})
Make sure you have the relations set in both User and Creator models.
Check out this topic for more info.
By using includes or joins instead of using creator.user you'll avoiding the unnecessary additional query. The downside is the syntax is now longer, you can maybe create your own getters to easily retrieve data instead of writing "includes" everytime.
Also assuming you're not aware of this method, I suggest you to read about the common N+1 problem with Rails & ActiveRecord. The same methods can solve a lot of problems for you.
Im building a Golf Cart rental app where Users can Book Golf Carts, what I need help with is implementing a Quantity and Availability check where when a cart is booked, the quantity is subtracted by 1 UNTIL the booking end date, and if quantity is currently 0 the cart is considered unavailable and unbookable. Im using Rails 5.2,
I have a Devise User model with added first and last name. A Cart model with name, description, quantity, and price columns. And a Booking model with start date, end date, user_id and cart_id columns. A User has_many bookings, a cart has_many bookings, and a booking belongs_to User.
I've been trying it on my own for days and no answers on here take into account the quantity aspect that I'm looking for.
This is a good example of a problem that could be solved either by computing values or by storing them in a database. I do not think you want to store "quantity" or "availability" in a database structure.
Per my comments, you should consider storing your "Carts" model (which I would rename "CartTypes") in memory. The only reason I can see to store it in a database table would be if you need to update the characteristics frequently--for example, if carts often break down and need to be fixed, you would need to change the total available carts for a given type.
In either case, you would have a "total_available" attribute for your CartType model. I would definitely not store a "quantity" attribute. Instead, you'll want to look at your bookings, determine the cart_type, start_date, and end_date, count the bookings for a particular cart_type on a given date, and subtract that number from total_available to determine availability.
How you write the query to do this depends on your schema and relationships. If you can be more specific, then I can provide a specific query.
How do i create a column which stores multiple values for a User model in Rails app?
Example:
I want to have a User model and store multiple fruit preferences. What type of fruit_preference would i need to add in order to store multiple fruit_preference values? Such as: fruit_preference: apple, orange, pear
I want to find specific users based on one of those fruits in my app later on.
Answering the original question - array data type.
But what you really need is associations.
class User
has_many :fruits
end
class Fruit
belongs_to :user
end
Having such setup you will be able to query users to find those with specific fruit:
User.joins(:fruits).where(fruits: {name: 'apple'})
As well, as having all user's fruits (because he can have multiple):
User.first.fruits
#=> collection of Fruit objects
This is way better, that storing user's fruits as a collection in database, because pretty quick maintaining/changing/updating these collections becomes hard.
Fairly new to rails and trying to understand which relationships to use before going forward.
I have two models: orders and items. This is a many to many relationship, but I'm unsure of which relationship to use.
Orders might have delivery time, quantity of items, etc.
Lastly, what would you call the model joining orders and items if using HMT?
If you need to know anything else about the relationship of the item on a particular order, you need HMT.
If your items change price in the future, do you want to know how much they were sold for on orders in the past?
In this type of requirement, I've always had many "LineItem" records for an order, and the line_item instances belong_to to the item and order, and record the pricing and/or quantity for that order.
HMT vs HABTM? There are so few times that all you need is a many-to-many, that I'd almost always go with HMT for the extra ability to add more information to the association.
This seems like a classic case of HABTM, and the example given in the Rails Guides is perfect. The choice comes down to whether you need any other data or logic on the join model itself. If so, then use the HMT, where you will create a third active_record model to serve as the join table. You can name that anything you want. But it seems like HABTM will work for you, and all you need to setup is the join table with the default name (items_orders) in your migration, and rails will take care of everything else for you.
class Order < ActiveRecord::Base
has_and_belongs_to_many :items
end
class Item < ActiveRecord::Base
has_and_belongs_to_many :orders
end
I'm building a course application system. The high school, undergraduate and graduate students are all able to apply for this course. They have to fill out some application form.
However, their information forms are similar, but not exactly the same. Every student has name, phone number, email, address, etc. But only undergraduate students have to provide their GPA, and graduate students is required to tell which lab they are researching at. There are other subtle differences...
So how should I deal with this? Make a big table, but leave 'GPA' column of high school students NULL? Or use three separate tables?
Moreover, there are some relation between Student(or, in three tables case, HighSchoolStudent, UndergraduateStudent and GraduateStudent) and other models. For instance, Course has many Students, Student has many Questions, and so on.
You can use a combination of STI and Store feature achieve this.
Declare a base model for Student with a text column called settings.
class Student < ActiveRecord::Base
store :settings
# name, email, phone, address etc..
end
class HighSchoolStudent < Student
# declare HighSchoolStudent specific attributes
store_accessor :settings, :gpa
end
class UndergraduateStudent < Student
# declare UndergraduateStudent specific attributes
store_accessor :settings, :attr1
end
class GraduateStudent< Student
# declare GraduateStudent specific attributes
store_accessor :settings, :attr2
end
In the sample above, instances of HighSchoolStudent will have an attribute called gpa.
You could go with the option you thought of like leaving GPA null, and set up custom validations for the model so it only checks depending on the student type. Single table inheritance is also an option, where you specify the different class names to use in a column on the database table, and then you simply add these classes in the model directory. You can see some documentation on it here: http://api.rubyonrails.org/classes/ActiveRecord/Base.html
I haven't tried STI before, but given what you stated above, I'd probably go for that route, branch off my code and would see how it pans out.