2014-09-06 57 views
0

我的問題不應該是複雜的,但我不明白爲什麼它不工作。我一直在尋找答案很多天,並嘗試了很多東西,但問題依然存在,所以如果我重複提問,我很抱歉。在我的應用程序中,我有3個模型用戶,課程&類別。相關的模型和簡單的形式在Rails 4

class Category < ActiveRecord::Base 
    has_many :courses, inverse_of: :category 
end 

class Course < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :category, inverse_of: :courses 
    accepts_nested_attributes_for :category 
end 

用戶模型的has_many:這裏的課程

是對課程和類別的架構:

create_table "categories", force: true do |t| 
    t.string "name" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    end 

    create_table "courses", force: true do |t| 
    t.string "title" 
    t.text  "description" 
    t.datetime "created_at" 
    t.datetime "updated_at" 
    t.integer "user_id" 
    t.integer "category_id" 
    t.string "address" 
    t.boolean "domicile" 
    t.decimal "lat" 
    t.decimal "lng" 
    t.string "city" 
    end 

    add_index "courses", ["category_id"], name: "index_courses_on_category_id" 
    add_index "courses", ["user_id"], name: "index_courses_on_user_id" 

在我的課程形式,我可以看到一個類別列表,我可以選擇一個,但當我創建一門新課程時,沒有爲課程分配category_id。我用simple_form和這裏的類別輸入:

<%= f.association :category, value_method: :id, include_blank: false %> 

而在我的課程控制器有這樣的:

def create 
    @course = Course.new(course_params) 
    @course.user = current_user 

    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 

而且這樣的:

def course_params 
     params.require(:course).permit(:title, :description, :user_id, :city, :address, :lat, :lng, category_attributes: [:id, :name]) 
    end 

回答

1

我覺得你不需要accepts_nested_attributes_for :category在你的課程模式,因爲它屬於一個類別。

在你的控制器中,你的course_params不允許有一個category_id參數,所以新課程沒有設置一個類別。你course_params應該是:

params.require(:course).permit(:title, :description, :user_id, :city, :address, :lat, :lng, :category_id) 

在您的形式,<%= f.association :category, value_method: :id, include_blank: false %>可以用(顯示類的名稱)來代替:

<%= f.association :category, label_method: :name, value_method: :id, include_blank: false %> 
+0

謝謝你這麼多的工作!我知道它根本不復雜,但看不到它是什麼...(只是稍微改正了一下,在你編寫course_id的參數中,但你的意思是category_id) – bTazi 2014-09-06 19:08:35

+0

@ user3499961是的,我編輯了我的答案:) – Thanh 2014-09-06 19:14:21