简体   繁体   中英

Can't write unknown attribute using rails_admin

Im' using rails_admin to save a project that has a category within. I didn't define project_id and category_id because I thought they should be created by rails. The problem I got were using the method def category_id=(id) defined in project model (see below). The error is:

can't write unknown attribute `project_id`

My models are:

Category

class Category < ActiveRecord::Base
  belongs_to :project, :inverse_of => :category

end

Project

class Project < ActiveRecord::Base
  has_one :category, :dependent => :destroy, :inverse_of => :project

  def category_id
    self.category.try :id
  end
  def category_id=(id)
    self.category = Category.find_by_id(id)
  end

end

My schema :

create_table "categories", force: :cascade do |t|
    t.string   "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "projects", force: :cascade do |t|
    t.string   "title"
    t.text     "text"
    t.string   "url"
    t.string   "key_feature"
    t.string   "image_1"
    t.string   "image_2"
    t.string   "image_3"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
  end

How do you connect Projects to Categories?

Base on your schema Projects table has no category_id.

Neither you Category table has project_id

I would add category_id to Projects table.

rails g migration add_category_id_to_projects category_id:integer 
rake db:migrate

The solution at the end was to manually add the project_id to categories table.

rails g migration add_project_id_to_categories project_id:integer 

Thanks @Misha for you suggestion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM