我是新來的鐵軌學習編碼的樂趣。我的目標是讓老師看到所有發佈有該老師的用戶的帖子。帖子屬於用戶,用戶屬於教師。Rails:未定義的方法錯誤與額外的ActiveRecord協會
型號:
class User < ActiveRecord::Base
belongs_to :teacher
has_many :posts, dependent: :destroy
class Teacher < ActiveRecord::Base
has_many :user_posts, through: :users, source: :posts
class Post < ActiveRecord::Base
belongs_to :user
老師控制器:
class TeachersController < ApplicationController
before_action :find_teacher, only: [:index]
def index
@posts = @teacher.user_posts
end
private
def find_teacher
@teacher = current_user
end
end
我與@posts掙扎。我一直在爲`user_posts'的未定義方法收到錯誤。我想知道我做錯了什麼以及在哪裏定義它。
Schema.rb(只是相關部分)
create_table "teachers", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "teachers", ["email"], name: "index_teachers_on_email", unique: true, using: :btree
add_index "teachers", ["reset_password_token"], name: "index_teachers_on_reset_password_token", unique: true, using: :btree
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "username"
t.string "TeacherEmail"
t.string "teacher"
end
我試圖搞清楚了這一點昨天一整天和今天上午我確實被卡死。在此先感謝您的時間。
除了Padmanaban Gokula所說的之外,它還有效。完成所有更改後,我必須重置數據庫。謝謝大家。這對我來說是一個重要的里程碑! –