STI
您正在尋找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
列:
$軌摹遷移AddTypeToAnimals
#db/migrate/add_type_to_animals.rb
class AddTypeToAnimals
def change
add_column :animals, :type, :string
end
end
-
修復
這種工作方式其實很簡單。
你可以打電話給你的Dog
和Cat
模型不受懲罰(沒有改變超出「正常」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 %>
+1爲您持續堅持與Rails! – 2014-09-12 10:19:22
爲你寫作答案 – 2014-09-12 10:20:26
你對每個模型有什麼其他專欄? – 2014-09-12 10:27:16