使用 rails 显示数组结果

Displaying an array result with rails

这是我的问题:

一切正常,但我的显示类似于 ["1","2","3"]。我想要 1 2 3。我尝试了所有 to_ 函数,但没有改变..

感谢您的宝贵时间。

model.rb:

validates :check, presence: true
validate :check_must_be_3

  private
    def checks_must_be_3
      if !check != 3
        errors[:base] << "You must select exactly 3 checks"
      end
    end

html:

<%= simple_form_for @answer do |f| %>
  <h3>Choose 3 answers</h3>
    <ul>
    <% (1..5).each do |x| %>
      <div class="checkbox">
        <label>
          <input type="checkbox" name="answer[check][]" id="optionsCheckbox<%= x %>" value="<%= x %>" />
          <%= x %>
        </label>
      </div>
    <% end %>
    <%= f.button :submit, "Submit", class: "btn btn-primary" %>
<% end %>

控制器:

private

def answer_params
    params.require(:answer).permit(check:[])
end

答案是数据库中的一个字符串。

只需在结果中添加以下几行

'["1", "2", "3"]'.split("[").pop().split("]").first.tr!('"', '')

不是最好的方法,但对你有用

另一个解决方案是

 '["1", "2", "3"]'.reverse.chop.reverse.chop.tr!('""', '')