我想在健身房添加一个地址,健身房只有一个地址,所以我也有可以拥有多个地址的用户,因为我想使用多态关系进行地址但 { {1}} 未显示
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"
答案 0 :(得分:2)
您是健身房的新地址,因此请将index
操作修改为
def index
if current_user.is_manager?
@gym = current_user.gyms.new
@gym.build_adress
end
end
OR
将fields_for修改为
= f.fields_for :adress, @gym.adress || @gym.build_adress do |adress_form|