Beginner, Ruby embedded on html page, doesn't

2019-08-30 05:34发布

I can not the results of database on browser when pushing it to open shift,while it works okay on my localhost machine, some one knows what is going there?

controler

class PostController < ApplicationController
  def index
   @post = Post.all
  end

  def show
  end

  def new
  end

  def edit
  end

  def delete
  end
end

model

 class Post < ActiveRecord::Base
   attr_accessible :email, :text, :title
 end

index.html.erb

<h1>index</h1>
   <% @post.each do |p|  %>
   <br />
   <%= p.email %>
   <%= p.title %>
 <% end %>

out put:

 index

 []

3条回答
爷的心禁止访问
2楼-- · 2019-08-30 05:40

ERB has different kind of tags. The main ones are:

  1. <% ruby code %>, which executes an operation in context,
  2. <%= ruby code %>, which executes an operation in context and outputs its result,
  3. <%# anything %>, which inserts a comment.

You typically use 2 to write things on the page, either on their own or inside a block or loop defined with 1 -- see what I meant when I said in context?

Your code should be:

<% @post.each do |p|  %>
  <br />
  <%= p.email %>
  <%= p.title %>
<% end %>

aside from that, the output you are getting, [], is the result of the first operation: <%= @post.each do |p| %>. It might mean that you've got an empty list.

查看更多
Deceive 欺骗
3楼-- · 2019-08-30 06:01

this

<%= @post.each do |p| %>

is wrong

Remove the "="

<% @post.each do |p| %>
查看更多
在下西门庆
4楼-- · 2019-08-30 06:03

You don't need to use equal sign for the loop in your html page

replace this line

<%= @post.each do |p|  %>

to

<% @post.each do |p|  %>

and make sure you will have some records in your post controller otherwise you will get empty array like this:

index
[]
查看更多
登录 后发表回答