如何从控制器方法打印视图中的字符串

时间:2013-06-13 21:01:29

标签: ruby-on-rails view methods controller concatenation

我有一个数据库,其中包含一周中每天的列,其中包含营业时间。业务关闭的任何一天在该列的表中都没有数据。

我的目标是在当天阅读这些数据并在我的视图中打印如下内容:

Monday: 8am - 5pm
Tuesday: 8am - 5pm
Friday: 8am - pm

跳过业务未开放的日子。在我的控制器中,我有我的索引方法:

    def index
        @locations = Location.all
    end

以及接受位置的其他方法:

    def gettimes(location)
    @campus = Location.where(:name => 'Tennille')
        sunday = @campus.sunday
        monday = @campus.monday
        tuesday = @campus.tuesday
        wednesday = @campus.wednesday
        thursday = @campus.thursday
        friday = @campus.friday
        saturday = @campus.saturday

        if @campus.sunday.empty
            @hours += "Sunday: #{sunday}<br />"
        end
        if @campus.monday.empty
            @hours +=  "Monday: #{monday}<br />"
        end
        if @campus.tuesday.empty
            @hours +=  "Tuesday: #{tuesday}<br />"
        end
        if @campus.wednesday.empty
            @hours +=  "Wednesday: #{wednesday}<br />"
        end
        if @campus.thursday.empty
            @hours +=  "Thursday: #{thursday}<br />"
        end
        if @campus.friday.empty
            @hours +=  "Friday: #{friday}<br />"
        end
        if @campus.saturday.empty
            @hours +=  "Saturday: #{saturday}<br />"
        end

        puts @hours
    end

我完全不知道如何调用此方法,更不用说在视图中打印结果了。

我的视图贯穿数据库条目,如下所示:

    <% @locations.each do |location| %>
    <%= location.etc %>

我甚至不确定我是否正确进行字符串连接,因此您将提供的任何帮助都将非常感谢!

1 个答案:

答案 0 :(得分:1)

我会在ApplicationHelper.rb

中创建一个方法
def show_time_board(location)
  board = ""
  ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"].each do |day_of_the_week|
    board += "#{day_of_the_week.capitalize}: #{location.send(day_of_the_week)}<br />" if location.send(day_of_the_week).present?
  end
  board
end

在视图中

<% @locations.each do |location| %>
  <%= show_time_board(location).html_safe %>
<% end %>

你应该使用ul和li作为html标签而不是