I am making a form for sign up and I have a class named ManagedCompany, that have an attribute named company of the class Company. The class Company have an attribute from another class named Address. So, there are compositions in those classes.
The classes are presented below:
app/models/managed_company.rb
class ManagedCompany
include ActiveModel::Model
def initialize
@company = Company.new
end
attr_accessor :name, :string
attr_accessor :company, :Company
end
app/models/company.rb
class Company
include ActiveModel::Model
def initialize
@address = Address.new
end
attr_accessor :category, :string
attr_accessor :name, :string
attr_accessor :address, :Address
validates_presence_of :category
validates_presence_of :name
end
app/models/address.rb
class Address
include ActiveModel::Model
attr_accessor :street, :string
attr_accessor :number, :string
validates_presence_of :street
validates_presence_of :number
end
My form:
<%= simple_form_for @managed_company do |form| %>
<%= form.input :company.address.street, autofocus: true %>
<% end %>
But this way did not work. The error message:
undefined method `address' for :company:Symbol
So, in the form (simple_form of ruby on rails), how can I access the attribute street from the address object?
Edit: add controllers code
app/controllers/managed_companies_controller.rb
class ManagedCompaniesController < ApplicationController
def new
@managed_companies = ManagedCompanies.new
end
def create
@managed_companies = ManagedCompanies.new(secure_params)
if @managed_companies.valid?
else
render :new
end
end
private
def secure_params
params.require(:managed_companies).permit(:name)
end
end
app/controllers/companies_controller.rb
class CompaniesController < ApplicationController
def new
@company = Company.new
end
def create
@company = Company.new(secure_params)
if @company.valid?
else
render :new
end
end
private
def secure_params
params.require(:company).permit(:name)
end
end
app/controllers/addresses_controller.rb
class AddressesController < ApplicationController
def new
@address = Address.new
end
def create
@address = Address.new(secure_params)
if @address.valid?
else
render :new
end
end
private
def secure_params
params.require(:address).permit(:street)
end
end
<%= form.input @company.address.street, autofocus: true %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.