这里我有3个型号 1.category 2.post 3.用户
帖子belongs_to类别 而且发布了belongs_to用户,当我尝试渲染一个新的帖子视图时,它说“未定义的方法`model_name'为nil:NilClass”
这是代码
的routes.rb
resources :categories do
resources :posts
end
模型
模型/ post.rb
class Post < ActiveRecord::Base
belongs_to :postable, polymorphic: true
模型/ users.rb的
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts, as: :postable
模型/ categories.rb
class Category < ActiveRecord::Base
has_many :posts, as: :postable
end
控制器
控制器/ posts_controller.rb
class PostsController < ApplicationController
before_action :find_category
before_action :find_post, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
before_action :authenticate_user!, except: [:index, :show]
def index
@posts = category.post
end
def show
@post = category.posts.find(params[:id])
end
def new
@post = current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
render 'new'
end
end
private
def post_params
params.require(:post).permit(:tittle, :content, :map, :bootsy_image_gallery_id, {postmages: []})
end
def find_post
@post = Post.find(params[:id])
end
def find_category
@category = Category.find(params[:post_id])
end
end
end
我需要在类别显示页面中有一个创建帖子链接,但结果永远不对。
查看
视图/帖/ new.html.erb
<%= simple_form_for @post do |f| %>
<% if @post && @post.errors.any? %>
<div class="alert alert-danger">
<p><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</p>
<ul>
<% @post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.input :title %>
<%= f.input :content %>
<%= f.button :submit %>
<% end %>
我不确定导致问题的原因是“未定义的方法`model_name'为nil:NilClass”,而我试图发布新帖子