2017-09-04 4 views
0

Je dois créer un nouvel enregistrement pour deux modèles appartenant au même modèle sur une méthode.Comment créer un nouvel enregistrement sur has_one pour deux modèles en même temps sur Rails?

Ceci est mon modèle

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 

Ceci est ma méthode de commande

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 

Puis, quand je soumets la forme i toujours eu cette erreur

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

Sur cette ligne

promotion.build_promotion_eng(promotion_eng_params).build_promotion_thai(promotion_thai_params) 

Comment puis-je résoudre ce genre de problème?

Merci!

Répondre

1

C'est parce que build_promotion_eng(promotion_eng_params) renvoie une instance PromotionEng.

Cela devrait fonctionner correctement.

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

Oh cela fonctionne très bien mais il semble que la validation ne fonctionne plus. Vous savez comment le faire fonctionner? – user3403614

+0

Quelle validation? Votre modèle de promotion n'a aucune validation. –