【问题标题】:Rails link_to for truncated html using helpers end up with undefined method使用帮助程序截断 html 的 Rails link_to 最终得到未定义的方法
【发布时间】: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。然后使用您调用的方法参数而不是@postspost。不是一个真正的答案,因为我不确定它是否正确。
  • 在最后一个示例中,您会收到该错误 (unexpected ')'),因为您确实确实在 end 前一行有意外的 ) .... 我会用正确的代码来回答

标签: ruby-on-rails


【解决方案1】:

有效的准答案:

<%= raw (truncate_html posts.content.html_safe, :length =>500, :omission => "...#{link_to 'Continue Reading', post_path(posts.url_name)}") %>

最终没有使用帮助器,但这有效。

【讨论】:

    【解决方案2】:

    正如我在评论中所写:

    在最后一个例子中你得到了那个错误:

    syntax error, unexpected ')', expecting keyword_end (SyntaxError)
    

    因为你在结尾前确实有一个意想不到的)。 结束的) 就在ommision: "..." 之后,所以你不需要另一个。

    您的辅助方法应如下所示:

    def post_truncate(&block)
      truncate(@posts.content,
        length: 250,
        separator: ' ',
        omission: "...") {
          link_to "Something", post_path(posts.url_name)
        }
    end
    

    我认为这是使用link_to 添加链接的正确方法,而不是像您在答案中那样使用字符串插值

    【讨论】:

      猜你喜欢
      • 2011-08-14
      • 1970-01-01
      • 2015-10-18
      • 2013-07-20
      • 1970-01-01
      • 2012-08-12
      • 2010-12-30
      • 1970-01-01
      • 2012-11-12
      相关资源
      最近更新 更多