Yi W0o
Yi W0o

Reputation: 38

rails wicked gem has_one association and nested form

On my form on has_one association the fields do not appear for a singular form.

<%= f.fields_for :pack_social_media_sur_mesure, @commande.pack_social_media_sur_mesure do |ff| %>

remains empty

i think i missed something...

My Models :

Commande model :

class Commande < ApplicationRecord
  belongs_to :user
  validates_presence_of :user
  has_one :pack_social_media_sur_mesure, dependent: :destroy
  accepts_nested_attributes_for :pack_social_media_sur_mesure, allow_destroy: true
end

PackSocialMediaSurMesure model :

class PackSocialMediaSurMesure < ApplicationRecord
  belongs_to :commande
  ...
end

My controller :

class CommandeStepsController < ApplicationController
  ...    
  def update
    @user_id = current_user.id
    @user = current_user
    @commande = @user.commande
    @commande.update(commande_params)
  end
  ...
  def commande_params
    params.require(:commande).permit(:id,..., pack_social_media_sur_mesure_attributes: [:id, ...])
  end
end

My form :

<%= form_for @commande, url: wizard_path, html: { class: "pack-slide" }, method: :put do |f| %>
  <%= f.fields_for :pack_social_media_sur_mesure, @commande.pack_social_media_sur_mesure do |ff| %>
    <%= ff.select :question1 %>
    ...
  <% end %>
  <%= f.submit %>
<% end %>

PS : I use wicked gem for this form, this why wizard_path.

Thx, Théo

Upvotes: 0

Views: 100

Answers (1)

Yi W0o
Yi W0o

Reputation: 38

Ok I find.

The reason why the fields do not appear is that I had already created an 'commande' but not a 'pack_social_media_sur_mesure'. Or the "wicked gem" takes us to the edit path but we cannot edit it if it does not exist.

The solution was to create the pack_social_media_sur_mesure when creating the 'order' as bellow :

class CommandesController < ApplicationController
  before_action :set_commande, only: [:show, :edit, :update, :destroy]

  ...

  def create
    @commande = current_user.create_commande(commande_params)
    if @commande.save
      if @commande.pack_social_media_sur_mesure == nil
        @commande.create_pack_social_media_sur_mesure(...)
      end
      redirect_to ...
    else
      render :new
    end
  end

  ...

  def set_commande
    @commande = current_user.commande
  end

Upvotes: 0

Related Questions