Rails 3 - multiple associations - ruby-on-rails-3

I have first table called Cars that contains the informations about color of the car, weight, price etc.
Then I have the second table, for example Other_informations. This table contains another informations about that car from the first table.
In the first table (Cars) is the name of the car. If I need to create an associations between these two tables, I can use:
car.rb
has many :other_informations
otherinformation.rb
belongs_to :car
In this case I have to set the name of one column in the table Other_informations on car_id and the associations will be created.
To this point is everything ok.
But now - I need just one association to add (from the table Other_informations to the table Cars - the same type of associations as the first).
I tried to do something like this:
car.rb
has many :other_informations
otherinformation.rb
belongs_to :car
belongs_to :car2
And then in the view used:
data.car2.name_of_the_car_from_first_table**
But this unfortunately didn't work me... can anyone help me, please, if is something like this possible to do?
Thank you in advance

I am not sure if I understand your question - do you want to have OtherInformation to be shared among different Cars? Like OtherInformation can belong to many different Cars?
You need some kind of many-to-many relationship then. Have a read:
http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many
EDIT (after reading your comments):
belongs_to car, :class_name => "Car", :foreign_key => "to_col1"
belongs_to another_car, :class_name => "Car", :foreign_key => "to_col2"
That assumes that your OtherInformation has two columns in the database table: to_col1 and to_col2 And here is how associations should work:
other_info = OtherInformation.first
first_car = other_info.car
second_car = other_info.another_car
second_car_name = other_info.another_car.name
#etc...

Related

How to create an association with from two columns

I have two tables, users and couples. The couples table has a pair of foreign keys lead_id and follow_id which point to the users table. I would like for the User class to have a has_many association to Couple which selects all couples in which a given user was a lead or a follow. I can do this using finder_sql and SQL like so:
has_many :couples, class_name: 'Couple', finder_sql:
proc { <<-SQL
SELECT couples.* FROM users
JOIN couples ON (couples.lead_id = users.id
OR couples.follow_id = users.id)
WHERE users.id = #{self.id}
SQL
}
This works fine, but :finder_sql is apparently deprecated, so I'm looking for another way. The best I have gotten is using a custom association scope like this:
has_many :couples, -> {
joins('JOIN couples ON (couples.lead_id = users.id OR couples.follow_id = users.id)')
.select('couples.*')
}, class_name: 'User', foreign_key: 'id'
But this causes ActiveRecord to return User objects rather than Couple objects. Is there a (non-deprecated) way to do this?
Sorry if the title is unclear, I'm open to suggestions.
Looking through the docs (http://guides.rubyonrails.org/association_basics.html) you may be able to get away with just this:
Users model:
has_many: :couples, as: lead
Has_many: :couples, as: follow
Couples model:
belongs_to :users
Also, look at the self joins section if you are attempting to relate leaders and followers.
Hope this helps.

Rails Form with has_many through - Which model to choose?

I have the following models:
Student has_many :subjects, :through => :classes
Subject has_many :students, :through => :classes
Class belongs_to :subject
belongs_to :student
The model class has an extra attribute (among the foreign keys to subject and students table) called level.
Basically I want to be able to have a form that will let the student to choose a subject and relate that subject to its record. So, I have this:
ClassesController < ApplicationController
def new
#list_of_subjects = Subject.all
# What should I do here?
end
My question is: How should I create the object for the form? From which model it should be, subject, student or class? I want to be able to create a record in the class table that would relate the student and the subject that the student has chosen, but I don't know if I am doing it wrong.
Thanks
I didn't think you could create a model called Class since it's a keyword, but that's neither here nor there...
First I think your controller and view should be using Student since it's the student that's selecting these things. Next, I think what you want to do is to add accepts_nested_attributes_for :class in your Student model which allows you to create an instance of the Class connector model from Student.
What you're trying to do sounds a little like something I tried to do. I have my full code there.
Using nested attributes to easily select associations in a form
I later refined it a bit in this question too to make the code less hideous:
Rails: How do I prepend or insert an association with build?
I know it's late, but I hope that helps.

Rails Model and foreign keys

Sorry if this has been asked before but I've tried searching and can't find exactly what I'm looking for.
I have two tables, one is called users and has a user_id field, the second is called users_friends and only has two fields, user_id and friends_id
I've spent the entire day trying many different variations and cannot get it to pull back the friends as user objects like I'm expecting.
The entire contents of my UsersFriends model is
belongs_to :user, :class_name => "User", :foreign_key => "user_id"
has_one :friends, :class_name => "User", :foreign_key => "id"
Thanks in advance,
J
I got a feeling that you do not understand how associations work. Please refer to: http://guides.rubyonrails.org/association_basics.html
Also you might find reading github page and/or code of acts_as_network plugin quite helpful and inspiring for building your "friends" feature. Please have a look:
https://github.com/sjlombardo/acts_as_network

Track sum of some fields in the association - "sum_cache"

I have tables 'orders' and 'items' with has_many association in the model.
class Order < ActiveRecord::Base
has_many :items
class Item < ActiveRecord::Base
belongs_to :order
Item consists of 'quantity' field, and Order consists of 'quantity_sum' field to track sum of associated items quantity.
For eg:
Order 1 : name='Toms shopping cart', quantity_sum=12
Item 1 : name='T-shirt', quantity=10
Itme 2 : name='Shoes', quantity=2
I have been looking for a way so that whenever new item is added/edited/deleted, the field 'quantity_sum' of Order gets updated automatically. Presently I have been using after_save method in Item, to update 'quantity_sum' field of Order.
Is there any other neat way of doing this besides 'after_save' ???
Similar to "counter_cache" for tracking count of associations, does rails have support for automatically keeping track of sum of some fields in the association?
Thanks
Remove the quantity_sum field from your table and add a quantity_sum method to the order class that sums up the quantity_values
class Order < ActiveRecord::Base
has_many :items
def quantity_sum
self.items.sum(:quantity)
end
end
Should do the trick. All you then need to do is remove any code you may have that updates the quantity_sum field. You will find that because the name of the method is the same as the field name (That you must not forget to delete) you won't have to refactor any of your code that makes use of it.
Obviously you need to be careful not to use this field unneccesarily like in a list of all orders in the system as this will be quite heavy on the database. O.K for a few hundred records but you'll notice a performance issue over thousands of orders.
Don't forget to remove that quantity_sum field from the order table
I think that this gem is what your'e looking for.
Look under "Totaling instead of counting" in the docs.
It should allow you to to something like this:
class Item < ActiveRecord::Base
belongs_to :order
counter_culture :order, :column_name => 'quantity_sum', :delta_column => 'quantity'
end
class Order < ActiveRecord::Base
has_many :items
end

Rails - many associations in one view

Thanks to stackoverflow users, stackoverflow helped me alot for my project until now. Now I face a new problem.
I already implemented this project http://img7.imagebanana.com/img/cnb46ti2/relationships.png (see Rails - data view from has_many and Has_many_and_belongs_to_many). For connecting positions and skills, I made an has_and_belongs_to_many relationship, because every position has many skills and every skills has many positions and for this table I didn't want to add some columns. The table 'positions_skills' puts both together.
Now I want to add 2 new tables.
current_qualification http://img7.imagebanana.com/img/bimfgvut/UebersichtQualifikationenbistqualifi.png
expected_qualification http://img7.imagebanana.com/img/72p0yj27/UebersichtQualifikationencsollqualif.png
if it's not clear what these tables with the qualification stars do: Every skill in a position has it's own level of qualification (for example for Position 1, you need to be competent in skill 1 alot (5 stars), but for Position 2, you need not so much knowledge about this skill(2 stars)). -> expected_qualification. And every employee is different good in each skill -> current_qualification
Question 1: The table 'expected_qualification' seems similar to the table 'positions_skills'. Am I right that if I add the table 'expected_qualification', than 'position_skills' is not necessary anymore? I just used 'position_skills' for connecting this n:m relationship for viewing employee's skills on show.html.erb, but it's also possible with 'has_many :through' associations if I understood right.
Question 2: Both tables are necessary for viewing these little stars on the view of employee's show.html.erb. (as you can see on my pictures. But right now I'm satisfied with numbers instead of Stars => 4 stars = 4 as integer in column). What did I do?
I created the table 'current_qualification' with rails generate scaffold current_qualification employee_id:integer skill_id:integer qualificationstars:integer
I added code into the models for has_many :through association
I filled the table for current_qualification
and now the tricky part: The employee controller! Because I already have an has_and_belongs_to_many association, the controller looks like this: def show #employee = Employee.find(params[:id], :include => { :position => :skills }) end .... How do I add :include => { :employee => { :current_qualifications => :skills} } for the has_many :through relation now into the already existing code? And which code lets me output the qualificationstars-column from the current_qualification-table for show.html.erb of employee?
Thanks in advance! And sorry for so much questions.