简体   繁体   中英

Brackets showing posts info in rails?

l am following a ruby on rails tutorial. I am having my posts info show up in brackets beside the caption on the posts. if you know how to fix it, please help!

Example=> "first post on PHOTOGRAM! [#<Post id: 1, caption: "first post on PHOTOGRAM!", created_at: "2017-09-04 03:24:25", updated_at: "2017-09-04 03:24:25", image_file_name: "instagram.jpg", image_content_type: "image/jpeg", image_file_size: 64169, image_updated_at: "2017-09-04 03:24:24">]"

posts controller

class PostsController < ApplicationController

  def index
    @posts = Post.all
  end
  def new
    @post = Post.new
  end

  def create
    @post = Post.create(post_params)
    redirect_to posts_path
  end

  private

  def post_params
     params.require(:post).permit(:image, :caption)
  end
end

app/views/posts/index.html.erb

<h1> Photogram </h1>

<%= @posts.each do |post| %>
  <%= image_tag post.image.url(:medium) %>
  <%= post.caption %>
<% end %>

new.html.erb

<%= form_for(@post) do |f| %>
  <%= f.file_field :image %>
  <%= f.text_field :caption %>
  <%= f.submit %>
<% end %>

Change your index.html.erb to

<% @posts.each do |post| %>
  <%= image_tag post.image.url(:medium) %>
  <%= post.caption %>
<% end %>

(Note the = that has been removed)

In ruby every statement has a return value. It might be nil but there is no void as known other programming languages. And ERB the opening tag <%= will output the following ruby code. So this line of code will output all the posts in @posts as well.

(this Answer is basically what "max pleaner" said in his comment, just with some remarks and explanations)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM