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
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
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.
ไม่มีความคิดเห็น:
แสดงความคิดเห็น