【发布时间】:2018-01-30 14:57:29
【问题描述】:
我正在尝试截断超过 250 个帖子以包含指向显示页面的链接。在我的控制器中,我有:
现在我的索引视图中有:
<% @posts.includes(:categories, :author).each do |posts| %>
<%= truncate_html posts.content.html_safe, :length => 250, omission:'...Continue Reading' %>
<%= link_to "...Continue Reading", post_path(posts.url_name)%>
它正确加载,没有错误。现在省略部分没有点击到新页面,所以我在link_to中添加了。然后我尝试了类似的东西:
<%= truncate_html posts.content.html_safe, :length => 250, link_to: "...Continue Reading", post_path(posts.url_name) %>
出现以下错误:
syntax error, unexpected ')', expecting => ", post_path(posts.url_name) );@output_buffer.safe_append=' ^
所以我决定尝试在助手中构建它,然后将助手插入。对于我的助手,我建立了:
def post_length
output = truncate(@posts.content, length: 250)
output += link_to('...Continue Reading', post_path(posts.url_name)) if post.content.size > 250
output.html_safe
end
然后将以下内容放入我的索引中:
<%= post_length %>
我最终得到了未定义的方法“内容”。我试过在助手中做:posts.content、post.content、@post.content 等。不起作用。我做错了助手吗?
我还尝试了以下方法:
def post_truncate(&block)
truncate(@posts.content,
length: 250,
separator: ' ',
omission: "...") {
link_to "Something", post_path(posts.url_name)
}
)
end
我最终遇到语法错误,意外的 ')',期待 keyword_end (SyntaxError)
【问题讨论】:
-
查看示例代码,
posts不是实例变量。我看不出它在哪里设置。它也感觉像是post(单数)而不是posts(复数)。帮助程序中未定义帖子的原因正是如此。@posts将可用,但它不是实例变量。post在这种情况下不存在。作为应该工作的修复(不管命名约定),将posts传递给post_length。然后使用您调用的方法参数而不是@posts和post。不是一个真正的答案,因为我不确定它是否正确。 -
在最后一个示例中,您会收到该错误 (
unexpected ')'),因为您确实确实在end前一行有意外的).... 我会用正确的代码来回答
标签: ruby-on-rails