目前,Rails 5应用程序中有以下设置:
class User < ApplicationRecord
has_many :addresses
accepts_nested_attributes_for :addresses
end
class Address < ApplicationRecord
belongs_to :user
end
相应的控制器如下所示:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
我有2个模型的用户和地址。
class User < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses
end
class Address < ActiveRecord::Base
belongs_to :user
end
我的控制器
def new
@user = User.new
@user.addresses << Address.new
@user.addresses << Address.new
目前正在试验Ember.js,而且目前还很喜欢它。我遇到的最大痛苦点是处理控制多个模型的复杂表单。在Rails中,这是一个相当直接的过程。
# Models
class Person < ActiveRecord::Base
attr_accessible :addresses_attributes
has_many :addresses
accepts_nested_attributes_for :addresses
end
class Address < ActiveRecord::Base
belongs_to :person
end
# View
<
所以我想要做的是用一种形式保存一堆数据。该数据的一部分是地址。这个地址被分成几种模式:国家、州、城市和地址。
我的问题是,老实说,我不知道如何在控制器中管理这个问题。我将分享我目前所拥有的,并希望有人能给我一个线索。
我应该为所有模特做accepts_nested_attributes_for 吗?如何连接所有这些继承字段或外键以处理这些信息?
国家模式:
class Country < ApplicationRecord
has_many :states
end
国家模式:
class State < ApplicationRecord
belongs_to :count
我尝试在表单元素之外使用表单数据。我希望将表单数据显示为普通文本。
控制器:
@addresses = ['Billing', 'Shipping']
@addresses.each do |a|
addresses.build(:address_type => a)
end
然后在我的form...for示例中...(Haml)
- fields_for :addresses do |a|
a.address_type #to just render 'Billing', etc.
或者..。
- fields_for :a
我有3个型号: class Address < ApplicationRecord
has_one :company_address
end class CompanyAddress < ApplicationRecord
belongs_to :address, dependent: :destroy
belongs_to :address_type
end class Company < ApplicationRecord
has_many :company_addresses
end 我正在从另一个应用程序获取JSON数据。 数据由一个公司