gpt4 book ai didi

ruby-on-rails - Rails 协会澄清

转载 作者:数据小太阳 更新时间:2023-10-29 08:46:42 24 4
gpt4 key购买 nike

如果有更有效的方法,我希望确认以下关联声明是否有效。

我有一个动物模型,您可以在其中创建狗、猫、兔子等,我还需要指定动物的品种,所以我想为每种动元素种类型建立一个模型,例如 DogBreed 和然后是 Cat Breed。

我在想每只动物只能有一个品种,这样的事情也行

 class Animal
has_one :dog_breed
has_one :cat_breed
end

class DogBreed
belongs_to :animal
end

class CatBreed
belongs_to :animal
end

每个模型的列是

Animal
name
description
size
breed

DogBreed
name

CatBreed
name

有没有更好的方法来解决这个问题?

我还将为每个品种模型​​的动物模型添加 accepts_nested_attributes_for

谢谢

最佳答案

性传播感染

您正在寻找 Single Table Inheritance :

#app/models/animal.rb
class Animal < ActiveRecord::Base
has_many :x
end

#app/models/dog.rb
class Dog < Animal
end

#app/models/cat.rb
class Cat < Animal
end

正如名称“单表继承”所暗示的那样,您的“依赖”模型将继承自。这意味着您将能够存储一个名为 animals 的中央表,您需要在其中添加一个type:

$ rails g migration AddTypeToAnimals

#db/migrate/add_type_to_animals.rb
class AddTypeToAnimals
def change
add_column :animals, :type, :string
end
end

--

修复

这个工作的方式其实很简单。

您可以毫无顾忌地调用您的DogCat 模型(没有超出“正常”Rails 工作范围的更改)。 type 列将自动填充:

#app/controllers/dogs_controller.b
class DogsController < ApplicationController
def new
@owner_dog = Dog.new
end

def create
@owner_dog = Dog.new dog_params
@owner_dog.save
end

private

def dog_params
params.require(:dog).permit(:x,:y,:z)
end
end

更新

在我们的 Skype 谈话中,您可能想要这样做:

#app/models/animal.rb
class Animal < ActiveRecord::Base
#fields id | breed_id | name | created_at | updated_at
belongs_to :breed
delegate :name, to: :breed, prefix: true
end

#app/models/breed.rb
class Breed < ActiveRecord::Base
#fields id | name | created_at | updated_at
has_many :animals
end

这将使您能够使用以下内容:

#app/controllers/animals_controller.rb
class AnimalsController < ApplicationController
def new
@animal = Animal.new
end

def create
@animal = Animal.new animal_params
end

private

def animal_params
params.require(:animal).permit(:name, :breed_id)
end
end

#app/views/animals/new.html.erb
<%= form_for @animal do |f| %>
<%= f.text_field :name %>
<%= f.collection_select :breed_id, Breed.all, :id, :name %>
<%= f.submit %>
<% end %>

关于ruby-on-rails - Rails 协会澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25805972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com