has_one, has_many & 多态关系

has_one, has_many & polymorphic relations

我想给健身房添加一个地址,而那个健身房只有一个地址,所以我也有可以有多个地址的用户,因为我想对地址使用多态关系,但是 fields_for 没有显示

型号

# 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

健身房控制器

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

嵌套形式

= 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"

迁移

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

你刚开始为健身房建立地址,所以修改index动作为

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

修改fields_for为

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