6

嗨,我想先说我是编码新手。

我有一个我认为可以通过两种方式解决的问题

A. 通过渲染部分

B. 通过更新控制器

(我可能完全错了,但这些是我怀疑的哈哈)

我有两个控制器/视图“评论”和“日志”。我希望它们都出现在同一页面上。

我怎样才能做到这一点?我尝试渲染部分但我总是得到一个错误。

我尝试了下面的代码:

这使我的评论显示在页面上,但是当我添加

@log = @user.logs.all 

对它来说,它不会像评论那样将所有日志都拉到页面上。

def show
  @user = User.find_by_name(params[:id])
  if @user 
    @reviews = @user.reviews.all
    render action: :show
  else
    render file: 'public/404', status: 404, formats: [html]
  end
end
4

2 回答 2

10

First things first. Views refer to actions in controllers. So there can be several views for each controller or even none.

So, if you want to render @reviews and @logs on the same page you should first instantiate both instance variables in the same action and then render both partials in the same action. How do you do that? Easy. First you got to the controller you just showed and edit that show action.

def show       
  # You can set the variable in the if-clause 
  # And you also need to use static finders with a hash as an argument in Rails4
  if (@user = User.find_by(name: params[:id]))
     @reviews = @user.reviews.all 
     @logs = @user.logs.all
  # You don't need to call render explicitly 
  # if you render the view with the same name as the action 
   else
     render file: 'public/404', status: 404, formats: [html]
   end     
end

Second: you go to your /app/views/reviews/show.html.erb template and put both partials there like this (this is just an example, adjust your markup to fit your needs).

<h1> Reviews and Logs</h1>
<div id="reviews_part">
 <%= render @reviews %>
</div>
<div id="logs_part">
  <%= render @logs %>
</div>

Now create 2 new partials /app/views/reviews/_review.html.erb and /app/views/logs/_log.html.erb and put all the needed markup there (use regular variables review and log to adress the repeating objects). Rails will automaticaly repeat those partials as many times as needed.

Or you can explicitely call the partial render

<div id="reviews_part">
  <% @reviews.each do |review| %>
   <%= render review %> 
        which is the same as
   <%= render partial:"reviews/review", locals:{review:review} %>
  <% end %>
</div>
于 2013-11-07T20:06:51.163 回答
0

这是在 HAML 中将局部渲染到视图中的方法:

=render :partial => "header"
%h2 Hello World
=render :partial => "footer"

您以这种方式渲染的每个部分都必须在同一个文件夹中创建。每个部分的名称必须以下划线 ( _ ) 开头。这应该是视图的目录:

- home
    - index.html.haml
    - _header.html.haml
    - _footer.html.haml
于 2020-06-16T15:35:42.383 回答