Rails在分配id时更新布尔属性

时间:2015-11-11 16:35:07

标签: ruby-on-rails ruby ruby-on-rails-4

我有一个has_many关联。我在同一个模型上的has_many个关联也很少依赖于布尔值。当我可以选择一种关联类型的ID时,我也有多重选择。我需要得到一个代码:当我将id指定给与布尔值== true的关联时,那么它与其关联的所有其他id应该变为false。

请考虑以下示例:

class Dealer < AR::Base
  has_many :campaigns
  has_many :published_campaigns, class_name: 'Campaign', -> { where(published: true) }
  has_many :unpublished_campaigns, class_name: 'Campaign', -> { where(published: false) }
end

class Campaign
  # attribute :published, :boolean
  belongs_to :dealer
end

# code
dealer = Dealer.find(params[:id])
dealer.campaigns.pluck(:id) # => 1, 2, 3, 4
dealer.published_campaigns.pluck(:id) # => 1, 2
dealer.unpublished_campaigns.pluck(:id) # => 3, 4
params[:published_campaign_ids] = [2, 3]
dealer.update_attributes(published_campaign_ids: params[:published_campaign_ids]) # => true

# campaign no 2 still will be published, campaign will become published, campaign no 1 will become unpublished, and campaign no 4 still will be unpublished
dealer.campaigns.pluck(:id) # => 1, 2, 3, 4
dealer.published_campaigns.pluck(:id) # => 2, 3
dealer.unpublished_campaigns.pluck(:id) # => 3, 4

如何以干净的方式制作它?

1 个答案:

答案 0 :(得分:0)

您可以使用添加到Dealer的方法来处理此问题,如下所示:

def setCampaigns(published, ids)
  if published
    self.published_campaign_ids = ids
    self.unpublished_campaign_ids = self.campaign_ids - ids
  else
    self.unpublished_campaign_ids = ids
    self.published_campaign_ids = self.campaign_ids - ids
  end
end

使用,很简单

dealer.setCampaigns(true, params[:published_campaign_ids]) # to publish campaigns

类似地,

dealer.setCampaigns(false, params[:unpublished_campaign_ids]) # to unpublish campaigns