【发布时间】:2014-09-06 15:30:02
【问题描述】:
我的问题一点也不复杂,但我不知道为什么它不起作用。我一直在寻找答案很多天并尝试了很多东西,但问题仍然存在,所以如果我重复问题,我深表歉意。在我的应用中,我有 3 个模型用户、课程和类别。
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 :courses
这是课程和类别的架构:
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
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-4 simple-form