【问题标题】:How to print string in view from controller method如何从控制器方法在视图中打印字符串
【发布时间】:2013-06-10 10:12:39
【问题描述】:

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

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

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 %>

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

【问题讨论】:

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


    【解决方案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 标签而不是

    【讨论】:

      猜你喜欢
      • 2017-01-09
      • 2016-07-23
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多