2015-11-17 53 views
2

我是新來的鐵軌學習編碼的樂趣。我的目標是讓老師看到所有發佈有該老師的用戶的帖子。帖子屬於用戶,用戶屬於教師。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 

我試圖搞清楚了這一點昨天一整天和今天上午我確實被卡死。在此先感謝您的時間。

回答

0

首先,如果用戶belongs_to :teacher,表Users的模式應具有列teacher_idinteger類型。

t.integer "teacher_id" 

然後,如果教師管理許多用戶,您必須在教師模型中定義它。然後,你可以創建一個方法來查詢由誰有教師用戶發佈的所有帖子:

class Teacher < ActiveRecord::Base 
    has_many :users 

    def user_posts 
    Post.where(id: users.map(&:id)) 
    end 
end 
+0

除了Padmanaban Gokula所說的之外,它還有效。完成所有更改後,我必須重置數據庫。謝謝大家。這對我來說是一個重要的里程碑! –

0

你缺少教師模型用戶模型關聯。

class User < ActiveRecord::Base 
    belongs_to :teacher 
    has_many :posts, dependent: :destroy 
end 

class Teacher < ActiveRecord::Base 
    has_many :users 
    has_many :posts, through: :users 
end 

class Post < ActiveRecord::Base 
    belongs_to :user 
end 
0

兩件事情打我:

  • 是有一個在users表中沒有teacher_id外鍵。你需要它爲belongs_to
  • 它應該是has_manyTeacher而不是belongs_to與用戶的關聯。

提示:遷移後,重新啓動服務器/控制檯。

相關問題