Rails:两个模型之间的相同“创建”操作有条件

时间:2016-12-08 00:40:20

标签: ruby-on-rails ruby activerecord model controller

使用三个主要模型建立网站:用户,帖子和健身房。用户应该可以从他们自己的模型(User.post)发布,或者,如果他们是健身房的管理员,则可以从Gym的模型(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模型发布。

非常感谢任何帮助,谢谢

2 个答案:

答案 0 :(得分:0)

我很好奇gym.gym_admin(以及因此'def create'下面的整行)的评估结果,因为我没有在其他任何地方看到引用。

我怀疑你想要改变

if (gym.gym_admin == current_user.id)

if (gym.gym_admin.id == current_user.id)

if (gym.gym_admin == current_user)

一旦这种关系正常运作。

此外,可以独立于用户是否是健身房管理员而发布,并且如果适用的话,发送post params the gym_id。然后通过以下方式访问:

/gym/:id
@posts = Post.where('gym_id = ?', params[:id])

/user/:id
@posts = Post.where('user_id = ?', params[:id])

答案 1 :(得分:0)

我修复了它,完全删除了条件逻辑;我只是在控制器中做了两个单独的自定义操作,并从不同的链接调用它们。即。 :actions =&gt; create_gym / create_user