我目前正在尝试为我的应用程序实现Category
模型。我试图以Users
可以有很多Categories
的方式设计它,Groups
也是如此。Categories
我遇到的问题是,我还希望能够拥有User
的正常列表,而不会将其分配给任何Group
或class CreateCategories < ActiveRecord::Migration[5.0]
def change
create_table :categories do |t|
t.string :name
t.text :description
t.references :categorizable, polymorphic: true, index: true
t.timestamps
end
end
end
class Category < ApplicationRecord
belongs_to :categorizable, :polymorphic => true
end
class User < ApplicationRecord
has_many :categories, :as => :categorizable
end
class Group< ApplicationRecord
has_many :categories, :as => :categorizable
end
。
我引用了rubyonrails.org/association_basics。
Category
我尝试通过rails c
创建新的Category(id: integer, name: string, description: text, created_at: datetime, updated_at: datetime)
Category.create( :id => 1, :name => 'Category_1', :description => '' )
begin transaction
rollback transaction
,但每当我尝试保存时,它都会回滚我的交易,可能是因为我错过了某些条件。
Category
我还觉得有更好的方法可以创建新的id
,因为我不应该手动设置hidden
。
感谢您的帮助。
答案 0 :(得分:1)
在rails 5中,无论何时定义belongs_to
关联,都需要默认存在关联记录。在尝试创建类别对象
category = Category.create(:name => 'Category_1', :description => '' )
category.errors.full_messages.to_sentence
如果您希望能够保存没有belongs_to关联的记录,则必须明确指定
class Category < ApplicationRecord
belongs_to :categorizable, polymorphic: true, required: false
end
答案 1 :(得分:1)
如果您尝试创建新类别并看到错误是需要存在可分类记录才能创建类别,一种简单的方法是将新对象本身作为可分类的对象它应该成功。
$ category = Category.new
=> #<Category id: nil, name: nil, description: nil, categorizable_type: nil, categorizable_id: nil, created_at: nil, updated_at: nil>
$ category.save
(0.1ms) begin transaction
(0.1ms) rollback transaction
=> false
$ category.errors.full_messages
=> ["Categorizable must exist"]
$ category = Category.new(categorizable: category)
=> #<Category id: nil, name: nil, description: nil, categorizable_type: "Category", categorizable_id: nil, created_at: nil, updated_at: nil>
$ category.save
(0.1ms) begin transaction
SQL (1.3ms) INSERT INTO "categories" ("categorizable_type", "created_at", "updated_at") VALUES (?, ?, ?) [["categorizable_type", "Category"], ["created_at", 2017-01-15 00:08:55 UTC], ["updated_at", 2017-01-15 00:08:55 UTC]]
(0.7ms) commit transaction
=> true
答案 2 :(得分:0)
这应该有帮助,Rails Cast on Polymorphic https://www.youtube.com/watch?v=6l9EAuev16k
您可以使用此...
创建多态记录`@category = @categorizable.User.new`
`@category = @categorizable.Group.new`
所以你不需要id。