[英]Ruby on rails and composition in OOP: How can I access attributes in simple_form?
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. 我正在填写注册表格,并且有一个名为ManagedCompany的类,该类具有名为Company的公司的属性。 The class Company have an attribute from another class named Address.
Company类具有另一个名为Address的类的属性。 So, there are compositions in those classes.
因此,这些类别中有一些作品。
The classes are presented below: 这些类如下所示:
app/models/managed_company.rb 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 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 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? 那么,如何使用形式(rails上的ruby的simple_form),如何从地址对象访问属性street?
Edit: add controllers code 编辑:添加控制器代码
app/controllers/managed_companies_controller.rb 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 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 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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.