【问题标题】:Truncate text and link to Read more截断文本并链接到阅读更多
【发布时间】:2013-03-29 15:22:38
【问题描述】:

在我的应用中链接到帖子时遇到了一个小绊脚石。我正在截断帖子的文本并提供“阅读更多”链接。查看帖子的区域有 2 个,一个供所有人(公共)使用,另一个供管理员用户编辑/删除帖子。

所以在我看来,我正在这样做

<% @toppost.each do |t| %>
    <div class="post-item">
      <h2><%= t.title %></h2>
       <ul id="newsHome">
        <li><%= date_output(t.published_on) %></li>
        <li><%= t.department.name %></li>
        <li>by Admin</li>
       </ul>
       <% if t.comments.length > 350 %>
        <p class="post-description"><%= truncate(t.comments, length: 350).html_safe %>
        <%= link_to '...Read more', t %></p>
        <% else %>
        <p class="post-description"><%= t.comments.html_safe %></p>

       <% end %>
    </div>
   <% end %>

但是,当点击阅读更多时,它会将我带到网址

/posts/:id

这实际上是管理员用户查看帖子的地方,因此此时用户将被重定向回主页,因为帖子控制器有

before_filter :authenticate_user!

所有帖子被公开查看的地方都在特定的新闻页面上,例如

localhost:3000/tynewyddnews
localhost:3000/woodside
localhost:3000/sandpiper
localhost:3000/outreach

我的问题是如何链接到该帖子在网站公共部分的位置。

使用 top_posts 方法的索引操作(方法见下文)

def index 
@title = 'Home'
@toppost = Post.top_posts

结束

top_posts 方法

def self.top_posts
#Array with each of the 4 departments - first record
top_posts = [
  self.tynewydd_posts.first,
  self.woodside_posts.first,
  self.sandpiper_posts.first,
  self.outreach_posts.first
]
#remove entry if nil
top_posts.delete_if {|x| x==nil}
return top_posts

结束

控制器

def tynewyddnews
  @title = 'Ty Newydd News'
  tynewyddpost = Post.tynewydd_posts.reverse
  tynewyddpost.pop
  @tynewyddpost = tynewyddpost
  @tynewyddpostlatest = Post.tynewydd_posts.first
end

型号

scope :tynewydd_posts, :include => :department, :conditions => {"departments.name" => "Ty Newydd"}, :order => "posts.published_on DESC"

其他部门还有另外3个范围,都一样找条件部门名

希望我补充了足够的信息,还有什么需要的请询问

编辑

一直在考虑这一点,但不确定我是否走在正确的轨道上,但对于每个帖子,我需要它链接到公共页面控制器中相应的新闻页面。

tynewyddnews
sandpipernews
outreachnews
Woodsidenews

所以在我的 link_to 中,我需要根据帖子的类型将路由传递给适当的操作。那么如何给每个帖子一个类型,然后链接到那个?

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 routes link-to


    【解决方案1】:

    哇,好的,我从哪里开始。

    例如,您需要一个指向该控制器操作的路由

    `get '/tynewyddnews' => 'news#tynewyddnews', :as => 'public_news' # gives you the route public_news_path
    

    在你看来

    = link_to 'Read More', public_news_path
    

    所以你,应该这样做。顺便说一句,您也可以使用 .truncate() 方法。您将长度作为参数传递,它会为您添加 ...

    【讨论】:

    • 谢谢,我更新了问题,不确定是否足够清楚。在索引操作中,我显示新闻部分的最新帖子,有 4 个。我如何设置要转到的路径特定的帖子取决于点击哪个帖子,它可以转到 4 个中的任何一个。你描述的方式给了我一个特定的路径,尽管这可能是我不够清楚的错
    • 是什么阻止您使用 if/else 语句?
    • 不确定我会选择什么,即要选择的参数,所以如果 params[:?] link_to 'newspath'
    猜你喜欢
    • 2017-02-21
    • 2019-03-14
    • 1970-01-01
    • 2011-01-15
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多