[ rails ] association

1-1 : break table to small table ( however, no reason to use this )

Classroom has_one :teacher
Teacher belongs_to :classroom

NOTE : singular :teacher, :classroom
FK is on belongs_to :classroom
In 1-1 case, we can do another way around

Teacher has_one :classroom
Classroom belongs_to :teacher

and FK is on :teacher

association method

classroom.teacher = teacher

Rails console

first_page = Page.new(:name=>'test')
first_page.subject
subject.page = first_page # save automatically when we made a relationship
first_page.subject = nil # remove relationship, but the subject is there
first_page.subject.destory # destroy subject
first_page.subject(true) # reload the subject, query database again and get the result 

1-m

Teacher has_many :courses
Classroom belongs_to :teacher

object return arrays

subject.pages << page # append, insert to database subject.pages.delete(page) # remove table link subject.pages.clear subject.pages.destroy(page) subject.pages.empty? subject.pages.size subject.pages.where(:visible=>true)

m-m

Course has_and_belongs_to_many :students
Student has_and_belongs_to_many :courses

join table
name : this_first_tables+”_”+second_tables
in alphabetical order
only store FK, no PK (:id => false)

migration file

create_table :join_table, :id => false do |t|
	t.integer this_first_tables_id
	t.integer second_tables_id
end
add_index :join_table, ["this_first_tables_id", "second_tables_id"]

# index will get dropped when we drop table


custom configurations

has_and_belongs_to_many :second_tables, :jointable=> 'join_table_name'
:class_name => "AdminUser"
:foreign_key => "test_fk_id"

m-m with additional columns in join table

create_table :join_tables do |t|
	t.references :fk_1
	t.references :fk_2
	t.string :another_column
	t.timestamps
end
add_index :join_tables, ["fk_1", "fk_2"]

table1

has_many :join_tables

table2

has_many :join_tables

 

traversing

section.section_edits.map{|se| ed.editor}

rich join
declaration

has_many :sections, :through =&gt; :section_edits

traversing

section.editors

INNER JOIN

section.editors << bob <—- cannot do this

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s