2

我正在尝试在 draper 装饰器中创建一个方法,该方法会吐出一个 form_for。我有一个用于在索引视图上搜索记录的表单,并且有几十个资源,所以如果可能的话,我真的想在一个地方维护这个逻辑(应用程序装饰器)。我的问题是我不知道如何在装饰器中呈现 form_for 。我遇到了 concat 和 capture 的一些用法来尝试完成此操作,但没有运气。我所能得到的只是几个要显示的div(也不是html,就像纯文本一样)。关于如何做到这一点的任何想法?这是我得到的代码:

def crud_index_search(search_obj)

h.concat "<div id='basic_search' style='display:none;'>"

search_form_for search_obj do |f|
  h.concat '<div class="input-append">'
  f.text_field :name_or_description_cont, :placeholder => 'Quick search ...', :id => 'search'
  h.concat "<button class='btn'><i class='icon-search'></i></button>"
  h.concat '</div>'
  link_to 'Advanced Search', '#', :id => 'advanced_search_btn', :class => 'pull-right'
end

h.concat '</div>'

h.concat "<div id='advanced_search' style='display:none;'>"
search_form_for search_obj do |f|
  f.condition_fields do |c|
    h.concat render "crud/partials/condition_fields", :f => c
  end
  h.concat "<p>#{ link_to_add_fields 'Add Conditions', f, :condition }</p>"
  f.submit 'Search'
  h.concat "#{link_to 'Basic Search', '#', :id => 'basic_search_btn', :class => 'pull-right'}"
end
h.concat '</div>'
end

在我看来……

<%= @categories.crud_index_search @search %>

任何帮助将不胜感激!

仅供参考,我已经将它放入一个部分并且有效,但是我需要添加一些更复杂的逻辑,这将使它在每个资源的基础上有所不同,所以部分对我来说并不理想。

谢谢

4

1 回答 1

1

Draper is excellent for putting logic pertaining to the view and does well at simple presentation, however you should in principle be leaving the content presentation to the view since that is what it is there for.

A pattern that I recommend is using the method on your Draper object to facilitate the logic and for each logic path render an appropriate partial.

So you might have something like this:

def crud_search_index(search_object)
  if search_object.something_to_check
    h.render 'shared/one_version_of_my_form'
  else
    h.render 'shared/another_version_of_my_form'
  end
end

And, even better, since your form is directly related to that search_object, I would actually create a Draper Decorator for that search object and put the method to generate the form on there instead of an "application" decorator.

Then your view is something like:

<%= @search.form %>

And if you need a reference to the @categories then pass it in to that method.

于 2013-08-05T21:56:14.303 回答