Badr Tazi
Badr Tazi

Reputation: 759

Associated model and simple_form in Rails 4

My problem shouldn't be complicated at all but I can't figure out why it isn't working. I've been searching for an answer for many days and tried a lot of things but the problem remains the same, so I apologize if I duplicate question. In my app I have 3 models User, Course & Category.

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

The User model has_many :courses

here's the schema for courses and categories:

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"

In my course form I can see the list of categories and I can choose one, but when I create a new course there is no category_id assigned to the course. I use simple_form and here's the category input:

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

And in my courses controller there's this :

    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

And this:

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

Upvotes: 0

Views: 83

Answers (1)

Thanh
Thanh

Reputation: 8624

I think you don't need accepts_nested_attributes_for :category in your Course model, because it is belongs to one category.

In your controller, your course_params did not permit a category_id params, so new course was not set a category. Your course_params should be:

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

In your form, <%= f.association :category, value_method: :id, include_blank: false %> may be replaced with (to display name of category):

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

Upvotes: 1

Related Questions