ActiveAdmin - 将本地传递给表单

时间:2013-07-15 01:11:09

标签: ruby-on-rails-3 forms activeadmin

在我的photos.rb文件中,我有:

ActiveAdmin.register Photo do
  form :partial => 'admin/forms/photo', :locals => { :events => Event.all }
end

在我的_photo.html.erb文件中,我希望能够访问事件的值,但它似乎无法检测到。我怎么能这样做?

根据评论的要求,这是我的表格:

<% if events.any? %>
  <%= form_for [:admin, @photo], :validate => true do |f| %>
    <!-- insert a bunch of standard field divs here -->
    <div class="actions" style="margin-top: 20px">
      <% if @photo.new_record? %>
        <%= f.submit 'Create photo' %>
      <% else %>
        <%= f.submit 'Update photo' %>
      <% end %>
    </div>
  <% end %>
<% else %>
  <div style="font-size: 14px">
    You cannot add photos until you have added at least one event.
  </div>
<% end %>

我收到的错误消息是events.any?行:

Completed 500 Internal Server Error in 108ms

ActionView::Template::Error (undefined local variable or method `events' for #<#<Class:0x007fdb8e841b80>:0x007fdb8a93e7a8>)

3 个答案:

答案 0 :(得分:2)

form do |f|
  f.render partial: 'admin/forms/photo', locals: { f: f, events: Event.all }
end

请注意,您需要从部分删除form_forsemantic_form_foractive_admin_form_for等,因为form do部分会覆盖admin/photos.rb部分否则会有两个嵌套表单。

示例部分:

# app/views/admin/forms/_photo.html.arb
if events.any?
  f.inputs do
    f.input :title, label: 'Etc'
    f.input :file
  end
  f.actions
else
  f.div 'You cannot add photos until you have added at least one event.', 
        style: 'font-size: 14px'
end

答案 1 :(得分:0)

另外想到这一点,如果您只想检查数据库中是否有任何事件,您可以直接在any拨打Class

<% if Event.any? %>
  do this
<% else %>
  do that
<% end %>

不将变量发送到partial,上面的代码结果为:

2.0.0p0 :004 > Event.any?
   (0.6ms)  SELECT COUNT(*) FROM "events"
 => true

并保留ActiveAdmin部分而不使用本地人:

ActiveAdmin.register Photo do
  form :partial => 'admin/forms/photo'
end

答案 2 :(得分:0)

form do |f|
    render partial: 'admin/forms/photo', locals: { value: 'random_data' }
end

您可以使用 f.render 渲染

请注意,需要partial:才能将本地人发送到表单

示例偏好

#app/views/admin/forms/_photo.html.arb
active_admin_form_for [:admin, resource] do |f|
    f.semantic_errors *f.object.errors.keys

    f.inputs do
       f.input :name
       f.input :random if (value == 'random_data')
    end
   f.actions
end