【发布时间】:2016-12-08 00:40:20
【问题描述】:
使用三种主要模型制作网站:用户、帖子和健身房。用户应该能够从他们自己的模型 (User.post) 发帖,或者,如果他们是健身房的管理员,则可以从健身房的模型 (Gym.post) 发帖。
我正在使用相同的帖子控制器和帖子表单向健身房或用户发布帖子,但控制器“创建”操作无法区分两者。
class PostsController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def create
if (gym.gym_admin == current_user.id)
@post = gym.posts.build(post_params)
if @post.save
flash[:success] = "Post!"
redirect_to "/gyms/#{gym.id}"
else
@feed_items = []
render 'static_pages/home'
end
else
@post = current_user.posts.build(post_params)
if @post.save
flash[:success] = "Post!"
redirect_to root_url
else
@feed_items = []
render 'static_pages/home'
end
end
end
def destroy
@post.destroy
flash[:notice] = "Post deleted"
redirect_to request.referrer || root_url
end
private
def post_params
params.require(:post).permit(:post_type, :title, :content, :picture, :body_parts,
:duration, :equipment, :calories, :protein,
:fat, :carbs, :ingredients, :tag_list,
:postable_id, :postable_type)
end
def correct_user
@post = current_user.posts.find_by(id: params[:postable_id])
redirect_to root_url if @post.nil?
end
def gym
@gym = Gym.find_by(params[:id])
end
end
还有模特:
class Post < ApplicationRecord
belongs_to :user
belongs_to :gym
belongs_to :postable, polymorphic: true
class User < ApplicationRecord
has_many :posts, as: :postable, dependent: :destroy
has_many :gyms
class Gym < ApplicationRecord
has_many :posts, as: :postable, dependent: :destroy
belongs_to :user
现在,这个创建动作只会从健身房的模型中创建帖子;如果我删除条件的前半部分,它只会从 User 模型中发布。
非常感谢您的帮助,谢谢
【问题讨论】:
-
它可能看起来更重复,但如果您使用两个不同的控制器,它可能会更简单。
标签: ruby-on-rails ruby activerecord model controller