Home > Blockchain >  Creating record from another controller Rails
Creating record from another controller Rails

Time:08-02

I want a Customization record to be created from the Campaign#create method.

Campaigns Controller

  def create
    @campaign = Campaign.new(campaign_params)
    if @campaign.save
      @campaignitem = Customization.create(campaign_id: 1, product_id: 1)
    end
  end

Campaign.rb

has_many :customizations

Customization.rb

  belongs_to :product
  belongs_to :campaign

I'm getting these 2 Activerecords errors when trying to save a Campaign

["Product translation missing: es.activerecord.errors.models.customization.attributes.product.required",
 "Campaign translation missing: es.activerecord.errors.models.customization.attributes.campaign.required"]

It's like if it won't get the campaign_id and product_id correctly

Please help! I've been so many hours with this now :(

CodePudding user response:

Since rails 5 there is a presence validation for belongs_to relations. So there must be a product and campaign records with id = 1 in your situation. If you don't want this validation you can simply add optional option like this:

belongs_to :product, optional: true

  • Related