ruby-on-railshas-manypolymorphic-associationshas-onefields-for

has_one, has_many & polymorphic relations


I want to add an adress to gym and that gym only have one adress, so also i have users that can have many adresses, cause that i want to use polymorphic relations for adresses but the fields_for it's not shown

Models

# Adress model
class Adress < ApplicationRecord
  include AdressTypeAsker
  belongs_to :adressable, polymorphic: true
end
# Gym model
class Gym < ApplicationRecord
  belongs_to :user
  has_one :adress, as: :adressable
  accepts_nested_attributes_for :adress
end
# User model
class User < ApplicationRecord
  include UserTypeAsker
  include UserAdressType
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
  has_many :adresses, as: :adressable
  accepts_nested_attributes_for :adresses
  has_many :gyms
end

Gym Controller

class GymsController < ApplicationController
  def index
    if current_user.is_manager?
      @gym = current_user.gyms.new
      @gym.adress
    end
  end
  def create
    if current_user.is_manager?
      @gym = current_user.gyms.new(gym_params)
      @gym.save!
      redirect_to gyms_path
    else
      redirect_to gym_path
    end
  end
  private
    def gym_params
      params.require(:gym).permit(:name, :open, :close, adress_attributes: [:name, :longitude, :latitude])
    end
end

Nested form

= form_for @gym do |f|
  .col.s6
    = f.label :open
    = f.time_field :open, class: "timepicker"
  .col.s6
    = f.label :close
    = f.time_field :close, class: "timepicker"
  .col.s12
    = f.label :name
    = f.text_field :name
  .col.s12
    = f.fields_for :adress do |adress_form|
      = adress_form.label :name, "adress name"
      = adress_form.text_field :name
      = adress_form.label :longitude
      = adress_form.text_field :longitude
      = adress_form.label :latitude
      = adress_form.text_field :latitude
    = f.submit "Add home adress", class: "waves-effect waves-teal btn-large gymtoy-primary z-depth-0"

Migration

class AddAdressToGyms < ActiveRecord::Migration[5.1]
  def change
    add_column :adresses, :adressable_id, :integer, index: true
    add_column :adresses, :adressable_type, :string
  end
end


Solution

  • you new to build address for gym, so modify index action as

      def index
        if current_user.is_manager?
          @gym = current_user.gyms.new
          @gym.build_adress
        end
      end
    

    OR

    modify fields_for as

    = f.fields_for :adress, @gym.adress || @gym.build_adress do |adress_form|