2016-07-23 79 views
-1

我已經爲UserCourse邏輯代碼設置了正確的邏輯。下面是我的文件,我目前有:創建新模型對象時用戶ID不會拾起

應用程序/模型/ course.rb

class Course < ApplicationRecord 
    belongs_to :user 
    validates_presence_of :course 
end 

應用程序/模型/ user.rb(使用設計):

class User < ApplicationRecord 
    # Include default devise modules. Others available are: 
    # :confirmable, :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable, 
     :confirmable, :omniauthable 
    has_many :courses 
end 

db/migrate/... create_courses.rb

class CreateCourses < ActiveRecord::Migration[5.0] 
    def change 
    create_table :courses do |t| 
     t.string :course, limit: 300 
     t.text :description 
     t.string :location 
     t.references :user, foreign_key: true 

     t.timestamps 
    end 

    add_index :courses, :course, unique: true 
    add_index :courses, :description 
    end 
end 

當我創建course一個新的對象,我得到下面的輸出:

1錯誤,無法儲存禁止這篇文章:

  • 用戶必須存在

堆棧跟蹤的問題:

Started POST "/courses" for 75.108.207.135 at 2016-07-22 22:33:28 -0500 
Cannot render console from 75.108.207.135! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255 
Processing by CoursesController#create as HTML 
    Parameters: {"utf8"=>"✓", "authenticity_token"=>"+RSKtrUI2jQ5DcXcndw7Lb9PN+mi6FJxGC3zX8oBLTnZdFeUTzTgZGc84V7onkW2UeNPTO2pHJ9cV2vx9yLjFQ==", "course"=>{"course"=>"Hello world", "description"=>"Hi", "location"=>"Hi"}, "commit"=>"Add Course"} 
    User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]] 
    (0.1ms) begin transaction 
    (0.1ms) rollback transaction 
    Rendering courses/new.html.erb within layouts/application 
    Rendered courses/new.html.erb within layouts/application (2.1ms) 
    Rendered layouts/_nav.html.erb (3.0ms) 
Completed 200 OK in 181ms (Views: 176.4ms | ActiveRecord: 0.5ms) 

應用程序/控制器/ courses_controller.rb

def create 
    @course = Course.new(course_params) 

    respond_to do |format| 
     if @course.save 
     format.html { redirect_to @course } 
     format.json { render :show, status: :created, location: @course } 
     else 
     format.html { render :new } 
     format.json { render json: @course.errors, status: :unprocessible_entity } 
     end 
    end 
    end 

有什麼我的模型創建過程中忽略了或者完全搞砸了?

+0

爲什麼在你的場模型驗證驗證過程的存在?課程是對象,而不是對象的領域。你不應該驗證用戶的存在嗎? – MarsAtomic

+0

請添加課程創建方法 – Sravan

+0

問題已更新。 –

回答

1

如果沒有CourseController#create方法,就很難確切地知道發生了什麼 - 但是您希望在那裏做的是使用has_many爲用戶對象添加的方法之一。

某事的效果:

user.courses.build(params[:course])user.course.create(params[:course])

兩個構建和創建可關閉的集合。

當然,Rails的導遊有更多的信息:http://guides.rubyonrails.org/association_basics.html#the-has-many-association

+0

問題已更新。 –

+1

@RodrigoArgumedo:閱讀完整的答案。這裏的猜測是正確的。 –

相關問題