为什么我将这个对象 params 数组附加到我的对象结果中? [英] Why I got this object params array attached to my object result in view?

查看:32
本文介绍了为什么我将这个对象 params 数组附加到我的对象结果中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 @forum_posts 的对象,它填充了我所有的论坛帖子.当我在视图中渲染它时,我得到了结果以及它的参数数组,如下所示:

I have this object named @forum_posts which populate all my forum posts. And when I render this in the view, I got the results along with the array of it's params like shown below:

这是我在 forum_posts.rb 控制器中定义@forum_posts 的方式:

Here is how i defined @forum_posts in the forum_posts.rb controller:

@forum_posts = ForumPost.all

即使我通过使用 ForumPost.all each .. 直接在视图中定义它,我仍然会发生这种奇怪的事情.

And even if I defined it directly in the view by using ForumPost.all each .. , I still got this weird stuff happening.

routes.rb

# app/config/routes.rb
resources :forums do
  resources :forum_posts, module: :forums
end

forums_controller.rb

# app/controllers/forums_controller.rb
class ForumsController < ApplicationController
  before_action :authenticate_user!, except: [:index, :show]
  before_action :set_forum, except: [:index, :new, :create]

  def index
    @forum_posts = ForumPost.all
  end

  def show
    @forum_post = ForumPost.new
  end

  def new
    @forum = Forum.new
    @forum.forum_posts.new
  end

  def create
    @forum = current_user.forums.new forum_params
    @forum.forum_posts.first.user_id = current_user.id

    if @forum.save
      redirect_to @forum
    else
      render action: :new
    end
  end

  private

    def set_forum
      @forum = Forum.find(params[:id])
    end

    def forum_params
      params.require(:forum).permit(:subject, forum_posts_attributes: [:body])
    end
end

index.html.erb 视图

<!-- app/views/forums/index.html.erb -->
<%= @forum_posts.all.each do |forum_post| %>
  <%= forum_post.id %> <br/>
<% end %>

推荐答案

只需删除第一行中的 = 如下:

Just remove = in the first line like this:

<% @forum_posts.all.each do |forum_post| %>
 <%= forum_post.id %> <br/>
<% end %>

请注意,如果您有 =,则您正在渲染.

Note that if you have = you are rendering.

<% %>  ----> Executes the ruby code within the brackets.

<%= %> ----> Prints something into erb file.

这篇关于为什么我将这个对象 params 数组附加到我的对象结果中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆