2017-02-13 20 views
0

我在我的courses_controller中有一個簡單的創建操作。我使用current_user.built命令來創建對象設計current_user表單提交「用戶不能空白」

courses_controller.rb

class CoursesController < ApplicationController 
    before_action :authenticate_user!, expect: [:index, :show] 
    before_action :set_course, only: [:show, :edit, :update, :destroy] 


    # GET /courses/new 
    def new 
    @course = current_user.courses.build 
    end 





    # POST /courses 
    # POST /courses.json 
    def create 
    @course = current_user.courses.build(course_params) 
    respond_to do |format| 
     if @course.save 
     format.html { redirect_to @course, notice: 'Course was successfully created.' } 
     format.json { render :show, status: :created, location: @course } 
     else 
     format.html { render :new } 
     format.json { render json: @course.errors, status: :unprocessable_entity } 
     end 
    end 
    end 





    private 
    # Use callbacks to share common setup or constraints between actions. 
    def set_course 
     @course = Course.find(params[:id]) 
    end 

    # Never trust parameters from the scary internet, only allow the white list through. 
    def course_params 
     params.require(:course).permit(:name, :description, :user_id) 
    end 
end 

當創建在瀏覽器中,我得到了下面的錯誤一門新課程:

1錯誤禁止從本課程被保存: 用戶不能爲空

這是表格視圖:

<%= form_for(@course) do |f| %> 
    <% if @course.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@course.errors.count, "error") %> prohibited this course from being saved:</h2> 

     <ul> 
     <% @course.errors.full_messages.each do |message| %> 
     <li><%= message %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :name %><br> 
    <%= f.text_field :name %> 
    </div> 
    <div class="field"> 
    <%= f.label :description %><br> 
    <%= f.text_area :description %> 
    </div> 

    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

任何想法可能是這裏的問題? 設計和CURRENT_USER方法工作在控制檯和其他型號

回答

1

在你的控制器精細,方法course_params不應讓user_id在參數傳遞,除非你希望用戶創建課程爲其他用戶。因爲你正在從current_user創建課程,所以不需要它。

還要檢查您的課程模型是否存在用戶驗證,而不是user_id。

+0

謝謝你的回答。 這是用戶和課程之間的一種habtm關係,這就是爲什麼我需要傳遞user_id。但是你的暗示關於:用戶而不是:user_id做了一個訣竅。謝謝! – Jan