2013-08-27 99 views
0

我希望每個學生都能夠在我的網站上發佈多條消息。屬於關聯表架構Ruby on Rails

因此每個學生的has_many:帖子 和後belongs_to的:學生(一個學生只)

的事情是我可以創造一個紀錄爲在軌控制檯中的學生,但不能後分配給學生?我有點困惑。具有許多模型的學生模型沒有屬於模型的屬性?

我有一個student.rb模型

class Student < ActiveRecord::Base 
    attr_accessible :first_name, :last_name, :email, :gender, :number, :college, :password, :budget, :picture 

    mount_uploader :picture, PictureUploader 

    has_many :posts 
end 

我有一個post.rb模型

class Post < ActiveRecord::Base 

    attr_accessible :message 

    belongs_to :student 

end 

這是我的架構

ActiveRecord::Schema.define(version: 20130827191617) do 

    # These are extensions that must be enabled in order to support this database 
    enable_extension "plpgsql" 

    create_table "posts", force: true do |t| 
    t.text "message" 
    end 

    create_table "students", force: true do |t| 
    t.string "first_name" 
    t.string "last_name" 
    t.string "email" 
    t.string "number" 
    t.string "college" 
    t.string "password" 
    t.float "budget" 
    t.string "picture" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

回答

1

您應該添加student_id整數列(如果還有這個專欄的索引,則會更好)到posts表。

要做到這一點,您可以鍵入控制檯:

bundle exec rails g migration add_student_id_to_posts student:references 
+0

我添加了'student_id'到我的架構,你怎麼在這名學生的ID列posts表添加一個索引?我可以運行遷移並將't.belongs_to:student'添加到帖子表嗎? – Jngai1297

+0

@ Jngai1297我編輯了我的答案。 –