【问题标题】:Rails: Undefined method `truncate' for main:ObjectRails:main:Object的未定义方法“截断”
【发布时间】:2017-03-15 10:28:26
【问题描述】:

我需要按照Rails API ActionView::Helpers::TextHelper 的说明在rails 控制台中执行此操作 我已经在下面的Stackoverflow Discussion 找到了我的问题的解决方案,但我认为这个问题可能对发布很有用。 如果你想让我删除它,请告诉我。

  1. 我想在我的 rails 控制台中创建一个ActionView::Helpers::TextHelper

    texthelper = ActionView::Helpers::TextHelper
    => ActionView::Helpers::TextHelper
    
  2. 我创建一个字符串

    string = "I want to call the truncate method"
    => "I want to call the truncate method"
    
  3. 我想在我的控制台上调用 truncate 方法,在这个字符串上。

    truncate(string, length: 25, omission: '... (continued)')
    => "And they f... (continued)"
    

当我在控制台输入时:

truncate("Once upon a time in a world far far away", length: 17, separator: ' ')

我收到了

undefined method `truncate' for main:Object

整个想法来自这篇文章.. Undefined method `truncate' in model

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    对于 rails 6 和 ruby​​ 2.6.*,可能会有一些问题,至少我在截断富文本时遇到了未定义错误的错误。所以,ActionText 和 Truncate,我找到了解决方案,它可能有用 =>

    <%= truncate(strip_tags(blog.body.to_s), length: 450) %>
    

    【讨论】:

    • ActionText 的另一种方法&lt;%= strip_tags(post.body.to_s).truncate_words(50) %&gt;
    【解决方案2】:

    我在下面的讨论Undefined method `truncate' in model找到了答案

    我应该使用以下命令在我的 rails 控制台中包含 ActionView::Helpers::TextHelper

    include ActionView::Helpers::TextHelper 
    

    然后我可以调用 truncate 方法。

    truncate(string, length: 17, separator: ' ')
    => "this is a tesf..."
    

    我现在的理解是,使用include 命令,来自ActionView::Helpers::TextHelper 的方法现在可以在控制台中使用。 truncate 方法可以在 text 上执行。

    【讨论】:

      【解决方案3】:

      添加到Ahsan's answer

      在处理 Rails 6 应用程序时,我尝试在具有 ActionText 属性的视图上添加调用 truncate 方法。

      就是这样,我有一个名为 About 的模型,其属性为title,ActionText 属性为body

      因此,当我尝试在我的视图中使用 body 的 ActionText 属性调用 truncate 方法时:

      <%= about.body.truncate(30) %>
      

      我得到错误:

      undefined method `truncate' for #<ActionText::RichText:0x00007fe5c4828488>
      

      这是我修复它的方法

      Ahsan's answer之后,我只是将代码行修改为:

      <%= truncate(strip_tags(about.body.to_s), length: 30) %>
      

      它就像魅力一样。

      您可以在 Rails 官方文档中阅读更多关于 truncate 方法的信息:ActionView Truncate

      就是这样。

      我希望这会有所帮助

      【讨论】:

        【解决方案4】:

        在 Rails 控制台中按照以下步骤操作:

        include ActionView::Helpers::TextHelper
        truncate(string, length: 25, omission: '... (continued)')
        => "Once upon ... (continued)"
        

        这里的“ActionView::Helpers::TextHelper”模块提供了一组格式化和转换字符串的方法。

        Truncate 方法位于 TextHelper 模块中,因此您必须将其包含在控制台中。

        【讨论】:

        • 感谢您的回复。如果您愿意通过编辑您的帖子来解释这是什么ActionView::Helpers::TextHelper 以及当我将其包含在我的 rails 控制台中时会发生什么,我很乐意接受您的回答
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-30
        • 1970-01-01
        相关资源
        最近更新 更多