使用模型关联时Rails-Simple Form和Devise current_user问题

时间:2016-05-31 06:19:25

标签: ruby-on-rails devise simple-form

我使用Devise作为我的身份验证系统和简单的表单。我在Groups#show和undefined method 'name' for nil:NilClass错误中收到NoMethodError。我使用模型关联将组和帖子绑定在一起。当我执行puts post.user.name时,它会在我的终端中正确显示,但该行会导致上述错误,并且由于某种原因它会引用群组#show。有什么想法吗?

路线

resources :groups do
    resources :posts
end

群组模型

class Group < ActiveRecord::Base
  validates :user_id, presence: true  

  belongs_to :user
  has_many :posts
  has_many :comments
  has_many :attachments
end

发布模型

class Post < ActiveRecord::Base
  validates :user_id, presence: true  
  validates :caption, presence: true

  belongs_to :user
  belongs_to :group

  has_many :comments, dependent: :destroy
end

组控制器

class GroupsController < ApplicationController
before_action :authenticate_user!

def new
    @group = current_user.groups.build
end

def create
    @group = current_user.groups.build(group_params)
    @group.user_id = current_user.id
    if @group.save
        redirect_to groups_path
    else
        render :new
    end
end

...
private

def group_params
    params.require(:group).permit(:group_name, :description, :user_id)
end

end

帖子控制器

class PostsController < ApplicationController

  before_action :set_post, only: [:show, :edit, :update, :destroy]
  before_action :owned_post, only: [:edit, :update, :destroy]  
  before_action :authenticate_user!

def index
    @posts = Post.paginate(page: params[:page], per_page: 3).order('created_at DESC')
    @post = current_user.posts.build
    @attachments = Attachment.all
end

...

def new
    @post = current_user.posts.build
end

def create
    @post = current_user.posts.build(post_params)
    @group = Group.find(params[:group_id])
    @post.group_id = @group.id

    if @post.save
      redirect_to groups_path
    else
      render :new
    end
end
...
private

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

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

def owned_post  
  unless current_user == @post.user
  redirect_to root_path
end

end  

end

基团/ show.html.erb

<%= render "posts/index" %> 
...

文章/ _index.html.erb

<%= render 'posts/form' %>
<%= render 'posts/posts' %>
...

文章/ _form.html.erb

<%= simple_form_for([@group, @group.posts.build]) do |f| %>
...

文章/ _posts.html.erb

<% @group.posts.each do |post| %>
<%= puts post.user.name %> ISSUE
<%#<%= render 'posts/post', post: post %>
<% end %>

1 个答案:

答案 0 :(得分:0)

解决方案:在询问Reddit Rails后,一位慷慨的用户提供了一个有效的解决方案。显然<%= simple_form_for([@group, @group.posts.build]) do |f| %>创建了一个新帖子并将其添加到groups.posts数组中,因此当它遍历_posts.html.erb并且没有用户时会导致问题。可以在此处找到更多信息:https://www.reddit.com/r/rails/comments/4lygix/unidentified_method_for_nil_class_devise_and/

但是用<%= simple_form_for([@group, Post.new(group: @group)]) do |f| %>替换上面的simple_form代码行似乎可以解决问题,正如上面reddit链接中的慷慨用户所建议的那样。