2015-08-16 46 views
1

在posts控制器创建行动:添加用户帖子的正确架构?

def create 
    @post = current_user.posts.build(post_params) 
    if @post.not_exists?(current_user) 
     if @post.save 
     #flash 
     redirect_to root_path 
     else 
     #flash[:error] 
     redirect_to root_path 
     end 
    else 
     #flash[:error] 
     redirect_to root_path 
    end 
    end 

Post模型:

class Post < ActiveRecord::Base 
    belongs_to :user 

    ##validations 


    def not_exists?(user) 
    return true unless user.posts.find_by(name: self.name) 
    end 

end 

我的问题:这是正确的建立我创建这样的行动?或者有更好的建筑设计?我认为这太胖了。

+1

我觉得这个帖子会更适合[code review](https://codereview.stackexchange.com/)网站。 –

回答

1

为什么不使用验证呢?

class Post < ActiveRecord::Base 
    belongs_to :user 

    validates_uniqueness_of :name, :scope => :user_id 
+0

非常感谢!这就是我一直在寻找的。 – Alexander