簡體   English   中英

如何使用 has_many_through 關聯允許我的活動管理資源的參數?

[英]How do I permit params for my active admin resource with a has_many_through association?

我在活動管理員中設置允許的參數時遇到問題。 文檔說“任何發送多個值(例如 HABTM 關聯或數組屬性)的表單字段都需要將一個空數組傳遞給 permit_params”。 這是我來自 admin/sample.rb 的代碼:

ActiveAdmin.register Sample do
  permit_params :title, :description, :file_type, :audio_data, :channels, :sample_rate, :file_size,
    categories: []
end

當我嘗試這個時,所有屬性都出現在我的活動管理表中,但categories中沒有任何內容。 我不確定我哪里出錯了。 我也嘗試過category_idssample_categories但它仍然沒有顯示在表格中。 我也嘗試向數組添加一個屬性,例如categories: [:name]但仍然沒有。

例如,在應用程序本身中,一切都按其應有的方式運行,並且我可以在創建sample時添加一個類別。 關於如何解決這個問題的任何建議? 這是一些相關的代碼。

模型/sample.rb

class Sample < ApplicationRecord
  ...
  has_many :sample_categories
  has_many :categories, through: :sample_categories
end

模型/類別.rb

class Category < ApplicationRecord
  has_many :sample_categories
  has_many :samples, through: :sample_categories
end

模型/sample_category.rb

class SampleCategory < ApplicationRecord
  belongs_to :sample
  belongs_to :category
end

控制器/samples_controller.rb

...
def sample_params
    params.require(:sample).permit(:title, :description, :audio, :file_type, :file_size, :sample_rate, :channels, :tag_list, category_ids: [])
end
...

您是否嘗試過您的Sample model中的 Accepts_nested_attributes_for function?

class Sample < ApplicationRecord
  ...
  has_many :sample_categories
  has_many :categories, through: :sample_categories

  accepts_nested_attributes_for :categories
end

如果可行,請先嘗試使用 test 或 rails 控制台。

另外請更新您的admin/sample.rb以允許來自categories嵌套屬性

ActiveAdmin.register Sample do
  permit_params :title, :description, :file_type, :audio_data, :channels, :sample_rate, :file_size,
    categories_attributes: [:id, :name, :etc]
end

注意:如果您使用的是活動管理員,則不需要samples_controller.rb CRUD controller 聲明

暫無
暫無

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

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