0

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:

enter image description here

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

@forum_posts = ForumPost.all

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 view

<!-- app/views/forums/index.html.erb -->
<%= @forum_posts.all.each do |forum_post| %>
  <%= forum_post.id %> <br/>
<% end %>
Ryzal Yusoff
  • 957
  • 2
  • 22
  • 49

1 Answers1

2

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.
oj5th
  • 1,379
  • 10
  • 25