Trung Tran
Trung Tran

Reputation: 13731

Merge method issue rails

Background: I have a model called Opportunity that has the "created_by" and "team_name" attributes, which correspond to a User model that has a "full_name" and "team" attribute. Thus, when a User logs in and creates a new Opportunity record, the systems created_by = User.full_name.

Problem (except from my Opportunity controller):

def create
  @opportunity = Opportunity.new(opportunity_params)
  @opportunity = Opportunity.new(opportunity_params.merge(:created_by => current_user.full_name))
  @opportunity = Opportunity.new(opportunity_params.merge(:team => current_user.team))
end

I use the opportunity_params.merge method twice. When this happens, only the last opportunity_params.merge line works. Right now, I use opportunity_params.merge to record current_user.team so the current_user.full_name does not record. Can anyone help?

Upvotes: 0

Views: 27

Answers (1)

infused
infused

Reputation: 24337

Merge your changes before you use the params:

merged_opportunity_params = opportunity_params.merge(
  created_by: current_user.full_name, 
  team: current_user.team
)

@opportunity = Opportunity.new(merged_opportunity_params)

Upvotes: 1

Related Questions