【问题标题】:Associated model and simple_form in Rails 4Rails 4 中的关联模型和 simple_form
【发布时间】: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


    【解决方案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)
    

    在您的表单中,&lt;%= f.association :category, value_method: :id, include_blank: false %&gt; 可以替换为(以显示类别名称):

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

    【讨论】:

    • 非常感谢您的工作!我知道它一点也不复杂,但看不出它是什么......(只是一点点更正,在你写 course_id 但你的意思是 category_id 的参数中)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多