Моя проблема не должна быть сложной, но я не могу понять, почему она не работает. Я много дней искал ответ и много чего делал, но проблема осталась прежней, поэтому я прошу прощения, если я повторяю вопрос. В моем приложении у меня есть 3 модели пользователя, курс & Категория.Связанная модель и simple_form в 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
Спасибо так много, что работал! Я знал, что это совсем не сложно, но я не мог понять, что это было ... (просто небольшая коррекция, в параметрах, которые вы написали Course_id, но вы имели в виду category_id) – bTazi
@ user3499961 да, я отредактировал свой ответ :) – Thanh