【问题标题】:Rails showing ActiveRecord_Relation in my viewRails 在我的视图中显示 ActiveRecord_Relation
【发布时间】:2021-03-04 07:33:49
【问题描述】:

我的问题是,当我调用我的模型 Question 并在 .each 中显示时,我的视图显示 ActiveRecord,但我现在不知道如何隐藏这个或在没有 ActiveRecord 的情况下显示我的问题的正确方式。

在我看来,内容显示如下:

<%= @questions = Question.all.order(:id).reverse_order %>

<% @questions.each do |question|  %>
  <% if @course.id == 1 %>

      <h5><%= link_to question.title, question ,  class: 'reply text-light text-decoration-none' %></h5>
<% end %>
<% end %>

【问题讨论】:

    标签: html ruby-on-rails


    【解决方案1】:

    What is the difference between <%, <%=, <%# and -%> in ERB in Rails?

    您可以使用&lt;% %&gt; 代替&lt;%= %&gt;

    <% @questions = Question.all.order(id: :desc) %>
    

    最好把它交给控制器:

    class QuestionsController
      def index
        @questions = Question.all.order(id: :desc)
      end
    end
    

    【讨论】:

      【解决方案2】:

      如果我想在视图中调用模型,我找到了一个解决方案,只需像这样创建一个输入 type="hidden":

      <input type="hidden" value="<%= @questions = Question.all.order(:id).reverse_order %>">
      

      【讨论】:

        【解决方案3】:

        你应该使用 Rails 提供的 url_helpers。请参阅link_to docs 下提供的示例。

        另外,我建议遵循https://stackoverflow.com/a/66470651/936494 的建议,并在您看来更改以下内容

        <h5><%= link_to question.title, question ,  class: 'reply text-light text-decoration-none' %></h5>
        

        <h5><%= link_to question.title, question_path(question),  class: 'reply text-light text-decoration-none' %></h5>
        

        如果您没有可用的 url_helpers,那么第二个参数应该是应用程序中资源的 URL。

        希望对您有所帮助。谢谢。

        【讨论】:

          猜你喜欢
          • 2020-01-30
          • 2017-05-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-04-08
          • 1970-01-01
          相关资源
          最近更新 更多