【发布时间】:2014-04-25 00:05:42
【问题描述】:
我目前正在开发一个允许用户从自己的帐户发帖的应用,但如果他们是群组或场所的管理员,他们也可以作为该实体发帖。我正在努力将多态关联的想法从其他一些问题中转换出来,因为通常它们都基于能够评论 多个事物而不是 来自 多个事物东西。
我认为我的主要问题是我的主页上有用户的帖子表单,因此 URL 中没有 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 的帖子
但我不知道它为什么要寻找尚未创建的 Post ID。任何帮助将不胜感激!
【问题讨论】:
标签: ruby-on-rails ruby polymorphic-associations