2015-08-16 15 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