0

我正在尝试让我的 Posts 控制器工作,但我不断收到以下错误消息:

undefined method 'each' for `#<Post:0x000000062820c0>`   

and : match ? attribute_missing(match, *args, &block) : super

我刚刚包含了属性方法,但错误仍然相同。我在下面发布我的控制器文件。谢谢您的帮助。

class PostsController < ApplicationController
include ActiveModel::AttributeMethods  #Just added this..the error message was the    

#same without it.


def new
 @post = Post.new
end

def create
@post = Post.new(post_params)

if @post.save
  redirect_to @post #.find(params[:id])
else
  render :new
end
end

def show
@post = Post.find(params[:id]) # show
end

private

def post_params
params.require(:Title).permit(:Body, :url) 
end

end

这是展示视图:

<h1>Posts</h1> 

<% @post.each do |post| %> 
Title: <%= post.Title %><br>
Body: <%= post.Body %><br>
url: <%= post.url %><br>
<% end %>
4

1 回答 1

0

SHOW操作:删除此行@post.each do |post| 并更改这些行:

Title: <%= post.Title %><br> Body: <%= post.Body %><br>

Title: <%= @post.title %><br> Body: <%= @post.body %><br>

INDEX动作:代替@post.each do |post|

<% @posts.each do |post| %> Title: <%= post.title %><br> Body: <%= post.body %><br>

为了能够使用它,您还需要添加index操作:

def index
  @posts = Post.all
end

建议:你的post_params方法写的不对。而是这样做:

def post_params
  params.require(:post).permit(:title, :body, :url) 
end

此方法所做的是将允许批量分配参数列入白名单。检查此以获取更多信息。

于 2014-08-20T13:50:31.887 回答