委托类型-RubyonRails



我仍在努力为Delegated Type功能找到一个好的解决方案,由于我没有找到任何好的更详细的指南,我想在这里询问。

我感兴趣的是DDH所说的:

Delegated types. With this approach, the “superclass” is a concrete class that is represented by its own table, where all the superclass attributes that are shared amongst all the “subclasses” are stored. And then each of the subclasses have their own individual tables for additional attributes that are particular to their implementation.

在他们的例子中,我看到他们在超类上使用了创建者,并且是子类的共享属性,他们在注释控制器中使用了这个属性,比如:

Entry.create! entryable: Comment.new(content: "Hello!"), creator: Current.user

在这种情况下,creator将始终相同,因此正确地实现为这样。

我的问题

(正如他们所提到的)如果你想让超类保留title属性(只是一个例子),所有其他子类都可以使用,我该如何处理?在这种情况下,标题是可变的(根据用户输入,每个子类的值都不同),它应该如何在子类控制器上实现。

随机示例:

注意:ofc我创建了可生产模块,并包含在子类模型中

# schema.rb
ActiveRecord::Schema.define(version: 2021_08_23_191445) do
create_table "laptops", force: :cascade do |t|
t.integer "usb_ports"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "mobiles", force: :cascade do |t|
t.integer "front_camera"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
create_table "Product", force: :cascade do |t|
t.string "title"
t.string "description"
t.string "productable_type"
t.integer "productable_id"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
end
end
# laptops_controller.rb
class LaptopsController < ApplicationController
def new
@laptop = Laptop.new
end
def create
@laptop = Product.create! productable: Laptop.new(laptop_params) # Here to add what for the title?
redirect_to @laptop
end
private
def set_laptop
@laptop = Laptop.find(params[:id])
end
def laptop_params
params.require(:laptop).permit(:usb_ports)
end
end
# _form.html.erb
<%= form_with(model: @laptop) do |form| %>
<div class="field">
<%= form.label :usb_ports %>
<%= form.number_field :usb_ports %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>

我应该像使用多态关联一样使用嵌套属性吗?有人有什么建议吗?或者,在每个子类和属性上添加title属性,在超类上只添加从未更改的属性?但是,那又有什么意义呢?

谢谢:)

如果其他人也面临同样的问题,在我寻找delegated_type时,accepts_nested_attributes_for选项不可用,因此我无法对通过delegated_type配置的关联对象使用嵌套表单。

但是:Rails 7delegated_type添加了对accepts_nested_attributes_for的支持https://github.com/rails/rails/pull/41717

和在超类上只添加从不更改的属性

我认为你误读了文档。直到今天我才知道这个功能(所以谢谢你引起我的注意),但据我所见,使用这样的超类的目的不是通过重用/共享所有记录都相同的字段来节省空间(如果它们真的对所有记录都一样,它们不必是字段。只需硬编码或放入配置文件中即可)。

因此,如果您正在创建Comments或Messages,则每个新的注释或消息都将创建自己的Entry(本例中的委派超类)。条目不会被共享,因此可以自由地拥有可变字段。

是的,由于这个特性似乎只是多态关联之上的一层糖,您可以/应该使用所有相同的方法(嵌套属性等)

最新更新