【问题标题】:How to print every row in ruby on rails如何在rails上打印ruby中的每一行
【发布时间】:2021-04-07 06:58:31
【问题描述】:

我要从oracle服务器查询数据。以下是我得到的,我想打印每一行。但看起来 "" 只打印最后一个结果,而 "" 什么也不打印。我感到很困惑。 我确定我连接到了 oracle 服务器,在这种情况下我要打印的是所有 10 个国家/地区的名称。

这是我的 helper.rb 文件

require 'ruby-oci8'
module HomeHelper
    def connect
        oci=OCI8.new('username','password','server/host')
        oci.exec('select name from country fetch first 10 rows only') do |record|
                puts record.join(',')
            end
    end
end

这是我的 html.erb 文件

<%= connect %>

【问题讨论】:

    标签: html ruby-on-rails frontend


    【解决方案1】:

    在 ERB 模板中,您有两种执行 ruby​​ 代码的基本方法。

    &lt;% name %&gt;(无 =)用于嵌入 逻辑
    &lt;%= name %&gt;(带有 =)用于嵌入

    要完成您想要的,您需要将两者结合起来。像这样的东西会将它们全部显示在您的视图中:

    <% collection.each do |entry| %>
      <%= entry.name %>
    <% end %>
    

    【讨论】:

    • 集合和条目应该是什么?我不知道。
    • collection 在这种情况下将是一个数组。 entry 是数组值的变量表示,entry.name 将在 entry 上调用 name 方法。我会通读Layouts and Rendering in Rails,因为您还需要设置@instance_variables 以将数据公开给您的视图。
    【解决方案2】:

    在 ERB 中,putsprint 实际上并没有像您预期的那样写入缓冲区。考虑这个例子:

    require 'erb'
    
    def connect
      puts "hello world"
    end
    
    template = ERB.new "<% connect %>"
    template.result(binding) # "\n"
    

    puts 输出到标准输出。在 Rails 的上下文中,这意味着它将在您运行服务器的终端中输出,而不是在您发送给客户端的响应正文中。如果要在erb中输出缓冲区需要使用&lt;%= %&gt;

    require 'erb'
    
    def connect
      "hello world"
    end
    
    template = ERB.new "<%= connect %>"
    template.result(binding) # "Hello world"
    

    如果您绝对必须在非输出代码块内输出文本(即 ),您可以使用concat method in Rails:

    require 'ruby-oci8'
    module HomeHelper
      def connect
        oci = OCI8.new('username','password','server/host')
        oci.exec('select name from country fetch first 10 rows only') do |record|
         concat record.join(',')
        end
      end
    end
    

    但这段代码实际上更多地属于模型(或类似存储库类的东西),然后是帮助器:

    require 'ruby-oci8'
    
    class Country < Struct.new(:name)
      @oci= OCI8.new('username','password','server/host')
    
      def self.top_ten
        [].then do |results|
          @oci.exec('select name from country fetch first 10 rows only') do |record|
            results << new(record)
          end
        end
      end
    end
    
    <%= Country.top_ten.map(&:name).join(', ') %>
    

    【讨论】:

    • 第一种方法有效,谢谢兄弟。而对于第二种方法,有一个错误说 superclass mismatch for class country。这是否意味着“Struct.new(:name)”不正确?
    猜你喜欢
    • 2020-01-26
    • 1970-01-01
    • 2018-07-16
    • 2021-08-16
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多