简体   繁体   English

Rails 6:仅当我使用我的控制器中的方法时才渲染部分内容

[英]Rails 6: Render a partial if only I'm using a method from my controller

I have a Users controller, with index , show , edit and destroy methods.我有一个 Users 控制器,带有indexshoweditdestroy方法。 In my layouts/ folder, I have a general-purpose user.html.erb layout that renders some partials.在我的 layouts/ 文件夹中,我有一个通用的 user.html.erb 布局,可以呈现一些部分。 These partials are of course producing errors due some of the info isn't available, like @user.name , for example.这些部分当然会产生错误,因为某些信息不可用,例如@user.name I've tried to render that partial always when I'm in a def show state, something like:当我处于def show状态时,我总是尝试渲染那个部分,比如:

<% if Users.show %>
<% render "shared/asides/users" %>
<% else %>
Other partials
<% end %>

I've tried several ways and I always get errors.我尝试了几种方法,但总是出错。 I feel totally lost even trying to find out this on the Rails documentation nothing seems to be indicated there too.即使试图在 Rails 文档中找到它,我也感到完全迷失,那里似乎也没有任何指示。

Your problem is, as you say, you're trying to display things associated with a user, like @user.name, but there is no @user.你的问题是,正如你所说,你试图显示与用户相关的东西,比如@user.name,但是没有@user。

So why not check for @user before showing the partial?那么为什么不在显示部分之前检查@user 呢? Or if you have a collection of users, I'm guessing @users?或者,如果您有一组用户,我猜是@users?

<% if @users %>
  <%= render "shared/asides/users" %>
<% else %>
  <%= Do something else %>
<% end %>

Of maybe a bit neater:也许有点整洁:

<%= render (@users ? path/to/partial_a.html.erb : path/to/partial_b.html.erb) %>

You can make a special layout for your action.你可以为你的动作做一个特殊的布局。 Then, at the end of action add layout to render.然后,在动作结束时添加要渲染的布局。

def show
  ...
  render layout: "custom_layout"
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM