How to created new record on has_one for two model on the same time on Rails?

44 views Asked by At

I need to create new record for two models that belong to the same model on one method.

This is my Model

class Promotion < ApplicationRecord
  has_one :promotion_thai ,dependent: :destroy
  has_one :promotion_eng ,dependent: :destroy
end

class PromotionThai < ApplicationRecord
  belongs_to :promotion

  mount_uploader :long_banner, PromotionImageUploader
  mount_uploader :square_banner, PromotionImageUploader
  mount_uploader :details_image, PromotionImageUploader

  validates :promotion_id, presence: true
  validates :title, presence: true
  validates :description, presence: true

  #validates :long_banner, presence: true
  #validates :square_banner, presence: true

end

class PromotionEng < ApplicationRecord
  belongs_to :promotion

  mount_uploader :long_banner, PromotionImageUploader
  mount_uploader :square_banner, PromotionImageUploader
  mount_uploader :details_image, PromotionImageUploader

  validates :promotion_id, presence: true
  validates :title, presence: true
  validates :description, presence: true

  validates :long_banner, presence: true
  validates :square_banner, presence: true

end

This is my controller method

def create
    promotion = Promotion.new
    promotion.build_promotion_eng(promotion_eng_params).build_promotion_thai(promotion_thai_params)

    if promotion.save
      flash[:success] = 'Success Created Promotion'
      redirect_to admins_promotions_path
    else
      errors_message = promotion.errors.full_messages.join(', ')

      redirect_to admins_promotion_new_path, :flash => { :error => errors_message }
    end
  end

Then when i submit the form i always got this error

undefined method `build_promotion_thai' for #<PromotionEng:0x007f9fdbcb0250> Did you mean? build_promotion

On this line

promotion.build_promotion_eng(promotion_eng_params).build_promotion_thai(promotion_thai_params)

How can i fix this kind of problem?

Thanks!

1

There are 1 answers

2
fedebns On BEST ANSWER

That's because build_promotion_eng(promotion_eng_params) returns an PromotionEng instance.

This should work fine.

promotion.build_promotion_eng(promotion_eng_params)
promotion.build_promotion_thai(promotion_thai_params)