วันพุธที่ 5 ตุลาคม พ.ศ. 2554

Ruby on Rails - Relationship Between Models

I would like to start with the basic knowledge I gained from the RoR tutorial at http://guides.rubyonrails.org/getting_started.html, how to associate a particular model to one another. In the RoR, simply just put the belong_to statement, followed by a name of the model you want to make the association, into the target model as the example code shown below.

class QuoteNews < ActiveRecord::Base
   belongs_to :quote
end

The statement defines that the QuoteNews class belong to the Quote class. Beside add the belong_to statement to the QuoteNews class, we have to define the relationship in the CreateQuoteNews class as well as the following code.

class CreateQuoteNews < ActiveRecord::Migration
  def change
    create_table :quote_news do |t|
      t.string :title
      t.text :content
      t.references :quote

      t.timestamps
    end
    add_index :quote_news, :quote_id
  end
end

The t.references statement define a foreign key column for the association between the two models. The add_index statement define an index for the association column. When we run the rake db:migrate command, the association between the models will be create in the database as we define in the CreateQuoteNews class.

Also, the has_many statement need to be added to the Quote class therefore; we can retrieve associated QuoteNews via the Quote class as shown below.

class Quote < ActiveRecord::Base
  validates :iname, :presence => true
  validates :bid, :presence => true
 
  has_many :quote_news
end  

Now we associate the two models togather, next we will create the controller for the QuoteNews model therefore; we can add a new quote news data to the database and then show it in the same page as the quote detail. I will share how we can do this later in the next post.

ไม่มีความคิดเห็น:

แสดงความคิดเห็น