Relationship between tables in Rails (Double relation with the same table) - ruby-on-rails

I'm new to rails, and I would like to get your help in this issue.
I have two tables Account and Transaction. each transaction shall have from account and to account. so when i add a transaction i shall select from the account table two times to get the FROM and TO accounts (list Selection in new transaction Form).
I'm using scaffold to generate the code and I can add only one relation to the table. Do you how to generate the relation with the account table two times
This is the generation code:
$rails g scaffold account a_name:string a_type:string a_amount:float
$rails g scaffold Transaction account_id:integer account_id:integer t_amount:float t_date:date t_desc:text

You will need two account_id columns in the transactions table, from_account_id and to_account_id, otherwise how will you tell the difference between the two?
rails g scaffold Transaction to_account_id:integer from_account_id:integer
Then, in your Transaction model, you will need to define the relationship properly:
belongs_to :from_account, class_name: 'Account'
belongs_to :to_account, class_name: 'Account'
As a side note, you really should avoid using scaffolding since it makes too many decisions and generalisations for you. You can use individual generators.
rails g model Transaction from_account_id:integer to_account_id:integer
rails g controller transactions

Related

Explanation on Rails Associations - Rails 4

i'm new to rails and your help and advise would be much appreciated as i am finding this challenging
Aim: i want the creator of the event to be able to select more than one user as
hosts for a created event (just like how facebook allows the creator of
a page to be be able to select users as admins of a created page). Is the below how my model and schema should be displayed?
i was aiming to build something like this image. Event1 i can select Ian & Jesse as hosts, Event2 i can also select Ian again as a host and select Emma
This is how i imagine it so far to be built (your guidance would be much appreciated):
models
user.rb
has_many events
event.rb
belongs_to user
host.rb
belongs_to user
has_many events
schema
users
name
email
events
title
address
user_id
hosts
user_id
event_id
Started writing this as a comment but realised it was getting too wordy.
your model is broken ... an event has many users .. it doesn't belong_to a single user.
What you have is a many to many relationship between users and events which needs resolving through a join table (aka associative/junction table). You have gone some way to resolving this with the hosts table though this goes against the rails convention.
What you want is something like:
models
user.rb
has_and_belongs_to_many :events
event.rb
has_and_belongs_to_many :users
and create a join table that references the two models
users table
name
email
events table
title
address
events_hosts table
user_id
event_id
The rails convention is for the join table to be named by joining the two names of the tables it is joining lexically ordered - i.e. events before hosts, concatenated together to give events_hosts.
Alternatively, you can also create a join model if you prefer:
EventHost
belongs_to :user
belongs_to :event
and modify the has_and_belongs_to_many to has_many :event_hosts in the other two models - the database schema will remain the same.

has_many by boolean value in rails

In my ruby on rails app i have two models: User and Item
In my user model I would like a relation where a user can have many items like this:
has_many :items
For the relationship I would not only use the user_id column in the items table.
When I do
User.includes(:items)
I would rather have all items where
- the items user_id belongs to the user (the classical way)
- or e.g. a boolean column (like all_users) is true
Can this be done with
has_many :items + any special options?
And how would it look like?
Thanks & Regards, Andreas
User.includes(:items) just instructs rails SQL builder to load all nested items withing loaded users.
That said,
User.includes(:items).all # will load all users with all nested items
User.includes(:items).where(name: 'Joe') # will load user(s) Joe and their items
this is done to minimize an amount of queries against the database.
Whether one wants to load all items, the query on Item should be used, e.g.:
Item.where(user_id: User.find_by_name('Joe').pluck(:id))

Rails associations - orders

So I have been trying to create a dummy application to try and learn Rails. The app I thought I could create is a coffee ordering app for a group of people in work.
So the website will have many users.
A user can create a coffee_order.
A coffee order contains orders for other individual users.
Each user can have one or more coffee_shop_items (e.g. latte,
cappuccino,danish, muffin, etc)
A coffee order also has an assignee, this is the person who is tasked
with going and getting the order.
So as a user, I create a coffee order, select an assignee, add users to the order, and add one or more coffee shop items to each user,
I am really struggling with how the database should be, and what the associations need to be, along with any join tables?
I am also trying to use nested attributes for the form entry.
Thanks in advance for help.
Update with some code I have tried to create a coffee order:
#coffee_order = CoffeeOrder.new(coffee_order_params)
params[:coffee_order][:user_coffee_orders_attributes].each do |user_order|
order = #coffee_order.user_coffee_orders.new(user_id: user_order[1][:user_id].to_i)
user_order[1][:coffee_shop_items].each do |item|
coffee_shop_item = CoffeeShopItems.find(item) if item != ""
# this line fails! see error below
#coffee_order.user_coffee_orders.coffee_shop_items << coffee_shop_item if coffee_shop_item != nil
end
end
error:
NoMethodError (undefined method `coffee_shop_items' for #<UserCoffeeOrder::ActiveRecord_Associations_CollectionProxy:0x42c6180>):
The coffee_shop_items belong to the order, not the user. After all, a user could probably create another order another day? You should probably also check out the rails documentation, which, IIRC actually contains a walk-through of a shopping cart application.
User has_many :coffes_orders
User has_many :coffee_orders_he_needs_to_get, class_name: "CoffeeOrder", foreign_key: "assignee_id"
CoffeeOrder belongs_to :user
CoffeeOrder belongs_to :assignee, class_name: "User"
CoffeeOrder has_and_belongs_to_many :coffee_shop_items
Coffee_shop_items has_and_belongs_to_many :coffee_orders

how to model an association with scaffold generator rails 4.2

Basic example:
1) I create a new rails project with following instruction:
rails new tut3
2) I generate my first scaffold model costumer
rails generate scaffold costumer name:string
3) I generate my second scaffold model product
rails generate scaffold product item:string costumer_id:integer
4) I run the migration (rake db:migrate) and after starting the server (rails s)
and adding a few costumers (e.g. Mario, Anna etc..) I go to the products page and I expected to get a costumer field with a dropdown table showing the ids of the costumers I've added but I see that I can insert in any id number I wish. Why so? Should the costumer field of the model product just restricted to the costumer IDs that I create in the costumer page? and how can I associate the product costumer field just with the costumer's name that I have created?
Hope my question is clear...))
Use
rails generate scaffold product item:string customer:belongs_to
rails generate scaffold does a lot of job for you, but it can't do each and everything for you.
You will have to do manually set other things for yourself. Starting with routes, you have to set them so that you could use something like customers/1/products or customers/2/products. scaffold won't set these routes for you.
resources :customers do
resources :products
end
When you mentioned customer_id while generating scaffold for products, that means a product belongs_to a customer, and you can check it in the code at app/models/product.rb. But now the question is, how the relation goes from a customer to a product. Can a customer have many products, or a customer can have only one product?
In app/models/customer.rb,
class Customer < ActiveRecord::Base
has_one :product # For having only product per customer
# has_many: products # Note that 's' at the end, this makes a customer have as many as products as possible.
end
Similarly, you need to change the view as well as the controller for both fields, and that is a whole lot of process. For that I recommend you to go through the basics of Rails, how do controllers and view work. After that, the stuff would be pretty much easy for you.

Seed a has_and_belongs_to_many table relationship

I have a project with 2 models linked through a habtm relationship and
would like to seed the default relationships values as they are fixed and needed for the
web aplication to work.
Can't seem to find a way to access the model join table and seed the default values to the object1_id, object2_id as the table is not linked to a model. It's currently being done via SQL directly on postgreSQL.
Any suggestions?
You would need to generate a join table if you have not already done so:
rails g migration CreateJoinTable users roles
And as long as you have habtm in their respective classes:
# app/models/user.rb
class User < ActiveRecord::Base
has_and_belongs_to_many :roles
end
Just push the object you are creating onto the associative array:
# db/seeds.rb
bill = User.create(name: "bill")
bill.roles << Role.create(title: "admin")
If you can think of any place where you would want to access the model directly, create the model. Otherwise direct sql query is probably fine.

Resources