Rails 4在创建之前默认设置登录用户的值

时间:2016-04-17 06:40:41

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

我有以下型号

members (id, name, company_id..)
companies (id, name, ...)
campaigns (id, company_id, ...)

创建广告系列时,我有以下内容

def create
    @campaign = Campaign.new(campaign_params)
    if @campaign.save
      redirect_to campaigns_path(@campaign)
    else
      render :new
    end
  end

我有AppController名为current_company的帮助方法,其ID我想设置为@campagin.company_id

这是将默认登录用户company.id设置为每个广告系列的最佳方法吗?

我可以遍历current_company并构建这样的查询吗?

@campaign = current_company.campaign.new(campaign_params)

1 个答案:

答案 0 :(得分:1)

您可以在模型中使用before_create回调来实现目标:

before_create :set_default

private

def set_default
  self.campaign_id ||= your_default_id
end

或者你可以直接在你的控制器中做同样的事情:

def create
  campaign_params[:company_id] ||= default_company_id
  @campaign = Campaign.new(campaign_params)
  if @campaign.save
    redirect_to campaigns_path(@campaign)
  else
    render :new
  end
end