多态评论

时间:2014-04-25 00:05:43

标签: ruby-on-rails ruby polymorphic-associations

我目前正在开发一个应用程序,允许用户从自己的帐户发布,但如果他们是团体或地点的管理员,他们也可以作为该实体发布。我正在努力将多态关联思想从其他一些问题中转换出来,因为通常它们都是基于能够在多个事物上评论而不是来自多个事物的东西。

我认为我的主要问题是我在主页上有我的用户帖子表格,所以它在网址中没有ID。

我的帖子控制器如下所示:

class PostsController < ApplicationController
  before_action :authenticate_user!, only: [:create, :destroy]
  before_filter :load_postable

  def index

  end

  def new
    @post = Postabe.posts.new(post_params)
  end


  def create
    @post = @postable.posts.build(post_params)
    if @post.save
        flash[:success] = "Post created!"
        redirect_to root_url
    else
      @feed_items = []
        render 'static_pages/home'
    end
  end

  def destroy
    @post.destroy
    redirect_to root_url
  end

  private

    def post_params
        params.require(:post).permit(:content)
    end

    def load_postable
      resource, id = request.path.split('/')[1, 2]
      resource_name = resource.singularize.classify
      if resource_name == "User"
        @postable = current_user
      else 
      @postable = resource_name.constantize.find(id)
      end
    end
end

和我的_post_form.html.erb部分:

<%= form_for ([@postable, @postable.post.new]), remote: true do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :content, placeholder: "Create a Post..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>

我的相关路线:

  devise_for :users, :controllers => { :omniauth_callbacks => "omniauth_callbacks", :registrations => "registrations" }
  resources :users, :only => [:index] do
    member do
      get :favourite_users, :favourited_users
    end
    resources :posts
  end

  resources :venues do
      resources :posts
  end

  resources :groups do
      resources :posts
  end

模型如下:

class Post < ActiveRecord::Base
    belongs_to :postable, polymorphic: true
end

class User < ActiveRecord::Base
        has_many :posts, as: :postable, dependent: :destroy
end

class Venue < ActiveRecord::Base
        has_many :posts, as: :postable, dependent: :destroy
end

class Group < ActiveRecord::Base
        has_many :posts, as: :postable, dependent: :destroy
end

似乎我一直收到错误

  

无法找到没有ID的帖子

但我不知道为什么它正在寻找一个帖子ID,如果还没有创建的话。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

您的控制器中有before_filter :load_postable。默认情况下,它将针对控制器中的所有操作运行,即使未指定id也是如此。 @postable = resource_name.constantize.find(id)引发错误,索引方法的id为nil。

将此行更改为:

before_filter :load_postable, except: [:index]