2015-11-05 95 views
1

我會問我的問題第一:創建的數據:通過關係

將這段代碼邏輯上工作,它是做(最佳實踐角度)正確的事?首先,讓用戶被傳遞給靜態訂閱方法看起來很奇怪

用戶和雜誌通過訂閱(定義見下文)有多對多的關係。你也可以看到,我通過連接來使用,而不是使用has而且屬於很多,這樣我們就可以定義一個訂閱模型。

創建用戶後,他們需要有默認訂閱。遵循單一責任原則,我認爲用戶不應該知道要訂閱哪些默認雜誌。那麼,在創建用戶後,如何創建默認訂閱。 user.likes_sports? user.likes_music?應該定義我們想要的訂閱方法。

我在正確的軌道上嗎?我沒有任何人審查我的代碼,任何代碼建議高度讚賞。

class User < ActiveRecord::Base 
    after_create create_default_subscriptions 

    has_many :magazines, :through => :subscriptions 
    has_many :subscriptions 

    def create_default_subscriptions 
     if self.likes_sports? 
      Subscription.create_sports_subscription(self) 
     end 
    end 
end 

class Subscription < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :magazine 

    #status field defined in migration 

    def self.create_sports_subscription(user) 
    Magazine.where("category = 'sports'").find_each do |magazine| 
     user.subscriptions << Subscription.create(:user => user, :magazine => magazine, :status=>"not delivered") 
    end 
    end 
    . 
    . 
end 

class Magazine < ActiveRecord::Base  
    has_many :users, :through => :subscriptions 
    has_many :subscriptions 
end 
+0

你想添加方法給你的用戶來檢查用戶「likes_sports?」或你想做什麼?在創建用戶後創建一些其他記錄? – Hendrik

+0

做了一個編輯,問題是在帖子的頂部 – user1438150

回答

1

在我看來,代碼太耦合了。這可以非常容易地失控。

要做到這一點,我認爲是創建一個新的服務/表單需要創建用戶的照顧你

class UserCreationService 

    def perform 
    begin 
     create_user 
    # we should change this to only rescue exceptions like: ActiveRecord::RecordInvalid or so. 
    rescue => e 
     false 
    end 
    end 

    private 

    def create_user 
    user = nil 
    # wrapping all in a transaction makes the code faster 
    # if any of the steps fail, the whole user creation will fail 
    User.transaction do 
     user = User.create 
     create_subscriptions!(user) 
    end 
    user 
    end 

    def create_subscriptions!(user) 
    # your logic here 
    end 
end 

然後調用代碼在您的控制器像這樣正確的做法:

def create 
    @user = UserCreationService.new.perform 
    if @user 
    redirect_to root_path, notice: "success" 
    else 
    redirect_to root_path, notice: "erererererooooor" 
    end 
end 
+0

很高興聽到另一個角度,非常感謝你 – user1438150

+0

不客氣:)。幾乎所有的東西都使用表單對象。 – Hendrik