1

我对 Rails 很陌生,我正在尝试使用 codecanyon 中的 jQuery newsticker 来显示已输入数据库的最新事件标题。此处示例:http: //codecanyon.net/item/jnewsticker-jquery-news-ticker/full_screen_preview/2137525

现在,它显示了数据库中的每个条目,以及事件表中的所有行,而不仅仅是标题,我认为脚本对此感到窒息。

我希望它只显示最近的 10 个事件。

在我的events_helper.rb助手中,我有:

module EventsHelper

    def populate_event
      @events.each do |event|
        content_tag(:li, link_to(event.title, '#'))
      end
    end

end

在我的events_controller.rb控制器中,我有:

class EventsController < ApplicationController
  before_filter :signed_in_user

  def create
    @event = current_user.events.build(params[:event])
    if @event.save
      flash[:success] = "Event created!"
      redirect_to root_url
    else
      render 'static_pages/home'
    end
  end

  def destroy
  end

  def show
    @event = Event.find(params[:id])
    @events = Event.recent
  end
end

在我的event.rb模型中,我有:

scope :recent, order(updated_at: 'DESC')

在我的_ticker.html.erb部分中,我有

<ul id="newsticker_1" class="newsticker">
   <%= populate_event %>
</ul>

当我在浏览器中查看源代码时,<li>列表中没有任何标签。

它看起来像这样:

<ul id="newsticker_1" class="newsticker" style="position: absolute; left: 10px;">
   [#&lt;Event id: 29196, title: "This is a title", tag: nil, privacy_level: 1, group: nil, image_url: nil, start_date: nil, end_date: nil, start_location: nil, end_location: nil, start_geolocation: nil, end_geolocation: nil, content: "Quia officiis voluptatum doloribus cum ut ea sed ve...", user_id: 2, created_at: "2012-12-09 03:51:26", updated_at: "2012-12-09 03:51:26"&gt;, #&lt;Event id: 29190, title: "This is a title", tag: nil, privacy_level: 1, group: nil, image_url: nil, start_date: nil, end_date: nil, start_location: nil, end_location: nil, start_geolocation: nil, end_geolocation: nil, content: "Dolor consequatur sed enim omnis asperiores fugit r...", user_id: 2, created_at: "2012-12-09 03:51:26", updated_at: "2012-12-09 03:51:26"&gt;
</ul>

它应该看起来像这样:

<ul id="newsticker_1" class="newsticker">
    <li>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</li>
    <li>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip...</li>
    <li>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum...</li>
    <li>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia...</li>
    <li>Bubble bubble ipsum dolor sit amet, consectetur adipisicing elit...</ li>
</ul>

更新:

遵循以下 Dimuch 的建议

这是代码在浏览器中的样子: 在此处输入图像描述

这就是 HTML 源代码正在做的事情:

在此处输入图像描述

4

2 回答 2

1

您误解了助手的用法。它不会将内容输出到生成的页面,而是返回一个插入到页面的值。

因此,您的辅助方法返回事件集合。尝试map与代替结合使用join

def populate_event
  @events.map do |event|
    content_tag(:li, link_to(event.title, '#'))
  end.join
end
于 2012-12-20T06:42:09.860 回答
1

按照 dimuch 的回答修复辅助方法后,使用 html_safe 调用该方法:

<ul id="newsticker_1" class="newsticker">
  <%= populate_event.html_safe %>
</ul>
于 2013-01-22T01:50:09.923 回答