我一直在尝试根据两个模型在一个表单上创建一个新记录来保存。截至目前,代码使用正确的ID在表中创建记录,但表格输入中没有保存值。模型如下:
class Account < ActiveRecord::Base
attr_accessible :alt_email, :c_address_id, :company, :do_not_call, :email, :first_name, :last_name, :mobile, :phone, :salutation, :subscribe, :title
belongs_to :user
validates :user_id, presence: true
has_many :account_addresses
has_many :addresses, through: :account_addresses
#accepts_nested_attributes_for :addresses, allow_destroy: false
attr_accessor :house, :street, :street2, :city, :state, :zipcode
end
class AccountAddress < ActiveRecord::Base
attr_accessible :account_id, :address_id, :deleted
belongs_to :account
belongs_to :address
end
class Address < ActiveRecord::Base
attr_accessible :city, :country, :full_address, :geo_verified, :house, :latitude, :longitude, :state, :street, :street2, :zipcode
has_many :account_addresses
has_many :accounts, through: :account_addresses
def self.create_from_user(opts)
a = Address.new
a.house = opts[:house]
a.street = opts[:street]
a.street2 = opts[:street2]
a.city = opts[:city]
a.state = opts[:state]
a.zipcode = opts[:zipcode]
a.country = opts[:country]
a.save
return a
end
end
create的控制器代码如下:
def create
success = false
@account = current_user.accounts.new
account_saved = @account.save
@address = Address.create_from_user({house: @account.house, street: @account.street, street2: @account.street2,
city: @account.city, state: @account.state, zipcode: @account.zipcode})
address_saved = @address.errors.none?
if account_saved && address_saved
account_address = AccountAddress.new
account_address.account_id = @account.id
account_address.address_id = @address.id
account_address.save
success = true
else
success = false
end
respond_to do |format|
if success
format.html { redirect_to @account, notice: 'Customer was successfully created.' }
format.json { render json: @account, status: :created, location: @account }
else
format.html { render action: "new" }
format.json { render json: @account.errors, status: :unprocessable_entity }
end
end
end
我看着使用accepts_nested_attributes_for执行此操作,但没有看到这对关系有何影响。对此以外的建议持开放态度。
查看尾部日志,它正在处理插入,如创建记录所示,但值显示
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)
表单
没什么特别之处提前感谢您的协助。