-3

现在在我的views文件夹中的application.html.erb中,我写了这个。

<p>List of all post IDs: <%= Post.all.each {|i| print i.id } %></p>

我希望它只输出每个帖子的 post.id。但相反,它显示了这一点

List of all post IDs: [#<Post id: 1, title: "Our First Post", content: "Content for our first post", created_at: "2012-11-24 11:22:02", updated_at: "2012-11-26 17:40:54", user_id: 1>, #<Post id: 3, title: "Our Second Post", content: "Content for our second post", created_at: "2012-11-24 11:51:32", updated_at: "2012-11-26 17:41:33", user_id: 2>, #<Post id: 8, title: "Our Second Post", content: "Content of Our mandatory Second Post", created_at: "2012-11-24 19:42:02", updated_at: "2012-11-27 20:46:57", user_id: 1>, #<Post id: 10, title: "C Post", content: "Hi I'm Cee nice to meet you", created_at: "2012-11-26 17:51:20", updated_at: "2012-11-26 17:51:20", user_id: 3>, #<Post id: 20, title: "11", content: "11", created_at: "2012-11-27 19:58:48", updated_at: "2012-11-27 19:58:48", user_id: 4>, #<Post id: 21, title: "22", content: "22", created_at: "2012-11-27 19:58:53", updated_at: "2012-11-27 19:58:53", user_id: 4>, #<Post id: 25, title: "I'm Super Singha!", content: "Yessar!!!", created_at: "2012-11-27 20:45:07", updated_at: "2012-11-27 20:45:07", user_id: 6>, #<Post id: 26, title: "Should this be a blog or a forums or a whatever-wha...", content: ";asljdfi;asfi;asdf;lasbfurbofioboboeifhosdsdbvisbvw...", created_at: "2012-11-27 20:46:28", updated_at: "2012-12-02 14:17:14", user_id: 1>, #<Post id: 27, title: "Hullow", content: "Yoyoyo", created_at: "2012-11-30 07:35:38", updated_at: "2012-11-30 07:35:54", user_id: 6>, #<Post id: 649, title: "um", content: "hey", created_at: "2012-11-30 12:20:58", updated_at: "2012-11-30 12:20:58", user_id: 2>, #<Post id: 82692, title: "LALALALAL", content: "hiopsdahfiosadhfioahfio", created_at: "2012-12-02 13:59:04", updated_at: "2012-12-02 14:22:41", user_id: 2>, #<Post id: 82693, title: "ggg", content: "fff", created_at: "2012-12-02 14:29:42", updated_at: "2012-12-02 14:29:42", user_id: 2>, #<Post id: 82694, title: "sick", content: "sick", created_at: "2012-12-02 14:41:32", updated_at: "2012-12-02 14:41:32", user_id: 5>]

我已经尝试过,puts而不是print,这也不起作用。

进一步:我还想根据预期结果为每个帖子显示页面创建一个链接,我该如何实现?

这是我的仓库:https ://github.com/nixor/cpblog ,这里是 heroku 网站:http ://still-plains-5469.herokuapp.com/

谢谢。

4

2 回答 2

0
<p>List of all post IDs: 
</p>
<%= Post.all.each do |e| %>
  <p>
    <%= e.Id %>
  <p>
  <%= link_to "Show", e %> 
<% end %>
于 2012-12-02T15:52:34.773 回答
0

问题在于您如何在此处使用 ERB 标签:

<%= Post.all.each {|i| print i.id } %>

每当您使用<%=时,都会呈现块的结果。在您的情况下,Post.all.each {}返回一个数组对象,这正是您在呈现的 HTML 中看到的。

为了打印出每个项目,您需要遍历项目 using<%然后打印出您想要 using 的内容<%=

<p>List of all post IDs: 
  <% Post.all.each |post| do %>
    <%= link_to post.id, post_path(post) %>
  <% end %>
</p>
于 2012-12-02T16:04:34.077 回答