1 一对多 Using Strong Parameters With Fields For & Nested Forms in Rails 4 http://www.rubyexperiments.com/using-strong-parameters-with-nested-forms/ class Account < ActiveRecord::Base has_many :people accepts_nested_attributes_for :people end class Person < ActiveRecord::Base belongs_to :account end class AccountsController < ApplicationController def new @account = Account.new @account.people.build (一对多这样写) http://www.tuicool.com/articles/Jjee6v (rails 中 create, new, build, save 的用法) @account.build_people (一对一这样写) end def create @account = Account.new(new_account_params) if @account.save respond_to do |format| format.html { redirect_to root_path, notice: "Account created successfully." } end end end private def new_account_params params.require(:account).permit( :id, :name, people_attributes: [:id, :email, :password, :password_confirmation] ) end end <% form_for @accountdo |f| %> <%= f.text_field :name %> <% f.fields_for :people do |pf| %> #注意这里 <%= pf.text_field :email %> <% end %> <% end %>
时间: 2024-11-03 22:02:01