您如何处理 Rails 部分的命名约定?

发布于 2024-09-01 04:43:18 字数 642 浏览 6 评论 0原文

例如,我可能有一个类似的部分:

<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" ... %>

你如何处理这个?将所有这些动作组合成一个部分并通过确定当前动作是什么来渲染不同的部分是一个好主意吗?

For example, I might have an partial something like:

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

which works for edit AND new actions. I also will have one like:

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

for the show action. So you would think that all your partials go under one directory like shared or something. The problem that I see with this is that both of these would cause a conflict since they are essentially the same partial but for different actions so what I do is:

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

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

How do you handle this? Is a good idea or even possible to maybe combine all of these actions into one partial and render different parts by determining what the current action is?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

余厌 2024-09-08 04:43:18

当我使用 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

如果你休闲一些规则,例如将您的部分放在共享目录中,然后放在模型目录中,然后始终使用 _form 进行编辑和新建,使用 _show 进行显示操作,然后它将起作用;)。当然,您需要定义 edit? 等方法:

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

或者也许有更好的方法来获取操作名称:)。

When I use shared directory, then inside I put model name and my partials have names like this:

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

If you want to have one line to render form or show partial, then you can add helper:

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 :).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文