我不太確定如何參考這個問題,但我正在 Ruby on Rails 中復制 Reddit。
在索引頁面上,我顯示了“帖子”表中的所有帖子。但是當我將它們全部顯示出來時,在最后一篇文章的末尾會出現一個文本,該文本用方括號括起來,包含表格中的所有資訊。我只想知道如何洗掉此文本。
問題圖片
這是用于顯示帖子的代碼:
<%= @posts.each do |post| %>
<div class="card p-3">
<small class="mb-2"><strong><%= link_to "s\\" post.sub.name, sub_path(post.sub) %></strong> Posted by <%= link_to "u\\" post.user.username, profile_path(post.user.username) %> <%= time_ago_in_words post.created_at %> ago</small>
<h4><%= link_to post.title, sub_post_path(post.sub, post) %></h4>
<p><%= truncate post.body, length: 200 %></p>
</div>
<% end %>
我的帖子控制器:
class PostsController < ApplicationController
before_action :authenticate_user!, except: [ :index, :show ]
before_action :set_post, only: [:show]
before_action :auth_subscriber, only: [:new]
def index
@posts = Post.all
end
def show
end
def new
@sub = Sub.find(params[:sub_id])
@post = Post.new
end
def create
@post = Post.new post_values
@post.user_id = current_user.id
@post.sub_id = params[:sub_id]
if @post.save
redirect_to subs_path(@post.sub_id)
else
@sub = Sub.find(params[:sub_id])
render :new
end
end
private
def set_post
@post = Post.find(params[:id])
end
def auth_subscriber
unless Subscription.where(sub_id: params[:sub_id], user_id: current_user.id).any?
redirect_to root_path, flash: { danger: "You are not authorized to view this page" }
end
end
def post_values
params.require(:post).permit(:title, :body)
end
end
uj5u.com熱心網友回復:
<% @posts.each do |post| %>
<div class="card p-3">
<small class="mb-2"><strong><%= link_to "s\\" post.sub.name, sub_path(post.sub) %></strong> Posted by <%= link_to "u\\" post.user.username, profile_path(post.user.username) %> <%= time_ago_in_words post.created_at %> ago</small>
<h4><%= link_to post.title, sub_post_path(post.sub, post) %></h4>
<p><%= truncate post.body, length: 200 %></p>
</div>
<% end %>
在 ERB<%=中用于將運算式的結果輸出到緩沖區。#each在 Ruby 中回傳,self所以您在頁面上看到的是隱式呼叫#to_s陣列的結果。
#each總是用于它的副作用而不是它的回傳值。在 ERB 模板的情況下,每次迭代都會寫入緩沖區。
這可能有點難以理解,但請記住模板中的任何明文都直接寫入緩沖區 -each只需執行 n 次即可。
uj5u.com熱心網友回復:
更改<%= @posts.each do |post| %>為<% @posts.each do |post| %>,注意第二個片段中缺少的“=”。
當您包含“=”時,輸出將.each列印在 HTML 中,在本例中為帖子陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/421025.html
標籤:
