1

例如,我可能有类似的部分内容:

<div>
  <%= f.label :some_field %><br/>
  <%= f.text_field :some_field %>
</div>

适用于编辑和新操作。我也会有一个像:

<div>
  <%=h some_field %>
</div>

为表演动作。所以你会认为你所有的部分都放在一个目录下shared。我看到的问题是这两者都会导致冲突,因为它们本质上是相同的部分,但是对于不同的动作,所以我要做的是:

<!-- for edit and new actions -->
<%= render "shared_edit/some_partial" ... %>

<!-- for show action -->
<%= render "shared_show/some_partial" ... %>

你怎么处理这个?将所有这些动作组合成一个部分并通过确定当前动作是什么来呈现不同的部分是一个好主意甚至可能吗?

4

1 回答 1

4

当我使用shared目录时,我在里面放了模型名称,我的部分名称如下:

shared/person/_show.html.erb
shared/person/_form.html.erb

如果你想用一行来呈现表单或显示部分,那么你可以添加助手:

def render_form_or_show(model)
  if edit? || new? 
    return render :partial => "shared/#{model}/form"
  elsif show?
    return render :partial => "shared/#{model}/show"
  end
  return ""
end

If you fallow some rules, like putting your partials in shared directory and then in model directory, and then always have _form for edit and new, and _show for show action, then it will work ;). Of course you need to define edit? etc. methods:

# Application controller
def edit?
  params[:action] == 'edit'
end

Or maybe there is better way to get action name :).

于 2010-05-07T11:36:52.200 回答