使用Active Admin进行验证

时间:2015-04-01 16:57:10

标签: ruby-on-rails validation activeadmin

我有两个模型,事件和图像:

class Event < ActiveRecord::Base
  has_many :images
  accepts_nested_attributes_for :images

  validates :date, presence: true
  validates :location, presence: true
  validates :name, presence: true
end


class Image < ActiveRecord::Base
  belongs_to :event

  mount_uploader :file, AvatarUploader

  validates :file, presence: true
  validates :event, presence: true
end

以下是我的迁移:

class CreateEvents < ActiveRecord::Migration
  def change
    create_table :events do |t|
      t.date :date
      t.string :location
      t.string :name

      t.timestamps
  end
 end
end


class CreateImages < ActiveRecord::Migration
  def change
    create_table :images do |t|
      t.string :file
      t.string :caption
      t.boolean :featured_image
      t.integer :event_id

      t.timestamps
  end
 end
end

我正在使用Carrierwave上传图片。如果没有内置任何验证,我可以毫无困难地使用此功能,但是我试图阻止图像上传,并且没有分配它的event_id。

目前,我的ActiveAdmin文件如下所示:

ActiveAdmin.register Event do
  menu label: "Events"

  permit_params :date, :location, :name, images_attributes: [:id, :file, :caption, :featured_image, :event_id]

  form :html => { :enctype => "multipart/form-data" } do |f|
    f.inputs "Event Details" do
      f.input :name
      f.input :location
      f.input :date, :start_year => 2000, :end_year => 2020

    f.inputs "Images" do
      f.has_many :images, :allow_destroy => true, :heading => false, :new_record => true, :html => { :multipart => true } do |p|
        p.input :event_id, :value => f.object.id
        p.input :file, :as => :file
        p.input :caption
        p.input :featured_image
      end
     end  
    end

  f.actions
end

有问题的主线是我将event_id分配给对象的id(事件)的值。

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:1)

更改

p.input :event_id, :value => f.object.id

p.input :event_id, input_html: { value: f.object.id }

并且你已经完成所有设置