fields_for

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

fields_for的相关文章

rails中一个窗体多个模型——fields_for

借助field_for可以生成表单来处理两个或更多模型对象的数据 先看一个官方的例子,一个表单中有person和permission两个模型,其中每个person包含一个permission <%= form_for(@person) do |person_form| %> First name: <%= person_form.text_field :first_name %> Last name: <%= person_form.text_field :last_name

Rails accepts_nested_attributes_for表单嵌套的利器

http://blog.csdn.net/kunshan_shenbin/article/details/7249713 http://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-fields_for http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html#method-i-accept

rails中accepts_nested_attributes_for应用

Model: class Blog < ActiveRecord::Base has_many :strip_rules accepts_nested_attributes_for :strip_rules, allow_destroy: true end class StripRule < ActiveRecord::Base belongs_to :blog attr_accessible :rule, :blog_id end 要实现在新建和修改blog时可以添加/删除任意多个strip