ユーザー、投稿、ジムの3つの主要モデルでサイトを作成します。ユーザーは、自分のモデル(User.post)から、またはジムの管理者であれば、ジムのモデル(Gym.post)から投稿することができます。Rails:2つのモデル間で条件付きの同じ「作成」アクション
私は同じポストコントローラとポストフォームを使ってジムやユーザーの投稿をしていますが、コントローラの "作成"アクションでは2つを区別できません。
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
今Rught、このcreateアクションはジムのモデルからの投稿を作成します。条件の前半を削除すると、Userモデルからのみポストされます。
すべてのヘルプは大歓迎ですが、あなたが
2つの異なるコントローラを使用すると、より反復的に思えるかもしれませんが、おそらくもっと簡単になります。 –