簡體   English   中英

委托類型 - Ruby on Rails

[英]Delegated types - Ruby on Rails

我仍在嘗試為委托類型功能找到一個好的解決方案,因為我沒有找到任何更好的更詳細的指南,我想在這里問一下。

我感興趣的是 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 我創建了 Productable 模塊並包含在子類模型中

# 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 %>

我應該像多態關聯一樣使用嵌套屬性嗎? 有沒有人有什么建議? 或者,在每個子類和屬性上添加標題屬性,在超類上僅添加永不改變的屬性? 但是,這又有什么意義呢?

謝謝 :)

並在超類上只添加永遠不會改變的屬性

我認為您誤讀了文檔。 直到今天我才知道這個特性(所以感謝你引起我的注意),但從我所見,使用這樣的超類的目標不是通過重用/共享字段來節省空間所有記錄都相同(如果它們對於所有記錄確實相同,則它們不需要是字段。只需對它們進行硬編碼或放入配置文件中)。

因此,如果您正在創建評論或消息,則每個新評論或消息都將創建自己的條目(本示例中的委托超類)。 條目不會被共享,因此可以自由地擁有可變字段。

是的,由於此功能似乎只是多態關聯上的一層糖,您可以/應該使用所有相同的方法(嵌套屬性等)

如果其他人面臨同樣的問題,當我尋找它時, accepts_nested_attributes_for選項對delegated_type不可用,因此我無法對通過delegated_type配置的關聯對象使用嵌套表單。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM