ActiveAdmin / Formtastic 可排序 has_many 通过关系

ActiveAdmin / Formtastic sortable has_many through relationship

我可能在这里遗漏了一些基本的东西,但我似乎无法让 ActiveAdmin 通过关系使用可排序的 has_many,并能够创建新记录。

所以给出以下模型

class User < ActiveRecord::Base

  has_many :user_videos
  has_many :videos, through: :user_videos

  accepts_nested_attributes_for :user_videos
  accepts_nested_attributes_for :videos

  ...
end

class UserVideo < ActiveRecord::Base

  belongs_to :user
  belongs_to :video

  accepts_nested_attributes_for :video

end

class Video < ActiveRecord::Base

  has_many :user_videos
  has_many :users, through: :user_videos

  ...
end

(我承认我有点乱扔 accepts_nested_attributes_for,希望有什么用)

Active Admin 设置是这样的(当然是 WIP):

f.inputs "User" do
  f.has_many :user_videos, heading: 'Videos', sortable: :order, allow_destroy: true, new_record: 'New Record' do |v|
    v.inputs for: :video do |video|
      video.input :video_url
    end
  end
  f.has_many :videos, heading: 'Videos', new_record: 'New Video' do |v|
    v.input :video_url
  end
end

f.actions

:user_videos 关联中的第一个 has_many 似乎没有呈现任何输入。如果那里有记录,我可以看到 video.input :video_url 实际上返回了带有 labelinputli 标记,但是没有任何内容呈现到页面。对于新记录,整个 v.inputs 位不会得到 运行(我需要先在那里创建子记录吗?)。

第二个 has_many 将起作用,因为您将能够添加记录并更新现有记录,但是无法排序,因为 order 列位于 UserVideos 模型。我将其包含在内更多是为了说明。

如果有人对此有任何指示,将不胜感激。 :)

由于似乎没有人有兴趣解决这个问题,我采用了另一种方法 - 我没有尝试让 ActiveAdmin / Formtastic 与现有模型结构一起工作,而是为交叉模型上的必要字段添加了 getter 和 setter。

class UserVideo < ActiveRecord::Base

  belongs_to :user
  belongs_to :video

  validates_with VideoValidator

  def video_url
    self.video = Video.create if video.nil?
    self.video.video_url
  end

  def video_url=(video_url)
    self.video = Video.create if video.nil?
    self.video.video_url = video_url
    # Video url is set via Active Admin, AA will not call save on the video as it does not realise it's changed
    self.video.save! if video.present? and video.valid?
  end

end

这样做意味着 Active Admin 不需要了解 Video 模型,并且可以只对 UserVideo 模型进行操作:

  f.has_many :user_videos, heading: 'Videos', sortable: :order, allow_destroy: true, new_record: 'New Record' do |v|
    v.input :video_url, :hint => (v.object.video.embed_code unless v.object.nil? or v.object.video.nil?)
  end

如果有人有实际的解决方案而不是解决方法,我很想听听,但除此之外,对于正在寻找同一问题的答案的任何人来说,这都是一个可能的解决方案。

哇!我知道我迟到了,但这是利用 :delegate method!

的绝佳机会

您的用户视频 class 看起来像这样

class UserVideo < ActiveRecord::Base

  belongs_to :user
  belongs_to :video

  validates_with VideoValidator

  delegate :video_url, :video_url=, to: :video
end

祝你好运!