我想在我的 Rails 应用程序中对相同的帖子有两种 View 。例如 - 在其中一个登录用户可以更新和编辑帖子,而在另一个中任何用户都可以查看它并对其发表评论或选择它。
我该怎么办?我需要单独上课吗?我知道每个 View 都需要一个单独的 View ,但是模型和 Controller 怎么样?
最佳答案
1.case:您的 View 将具有类似的内容,但只有登录用户才会有编辑等额外选项。
您应该使用部分 View ,并且在主视图中您应该编写如下内容:
<% if signed_in? %>
<%= render 'edit_form' %>
<% end %>
请记住,部分的名称应始终以下划线开头,因此在这种情况下,您的部分将被称为 _edit_form.html.erb
或 _edit_form.html.haml
,取决于您使用的是什么。
2.case:根据用户是否登录,您想要呈现完全不同的 View ,那么您应该在 Controller 中处理它:
def show
if signed_in?
render 'show_with_edit'
else
render 'show_without_edit`
end
end
您的文件将被命名为 show_with_edit.html.erb
和 show_without_edit.html.erb
此外,如果您的登录用户 View 名为 show
,那么您可以执行以下操作:
def show
render 'show_without_edit' unless signed_in?
end
3.case:如果您想基本上更改所有内容,具体取决于用户是否登录,您可以创建一些自定义方法并在原始方法中调用它们像这样的 Action :
def show
if singed_in?
show_signed_in
else
show_not_signed_in
end
end
private
def show_signed_in
# declaring some instance variables to use in the view..
render 'some_view'
end
def show_not_signed_in
# declaring some other instance variables to use in the view..
render 'some_other_view'
end
关于ruby-on-rails - 在一个 Action 中渲染不同的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15923664/