accepted_nested_attributes_for在Rails 3中使用实际形式

时间:2011-04-19 13:51:19

标签: ruby-on-rails ruby ruby-on-rails-3

使用Ruby on Rails 3:

我半理解accepts_nested_attributes_for 假设如何工作,但我无法找到一种实用的方法来实现它。例如,如果有人想在其用户页面中添加最近的位置:

user.rb

class User < ActiveRecord::Base
  has_many :locations
  accepts_nested_attributes_for :locations
end

location.rb

class Location < ActiveRecord::Base
  belongs_to :user
end

位置表

location
  -location
  -length_of_stay
  -user_id

关于如何在用户视图_form.html.erb中实现此功能的任何想法?文档没有谈论任何关于视图的内容。

我尝试使用railscast教程,但它无法正常工作 - 我相信演员是为rails 2.3制作的,但我不确定3中是否有不同的用法。

1 个答案:

答案 0 :(得分:4)

accepts_nested_attributes需要在有一些链式模型时实现,并希望以一种形式创建和编辑它们。
例如:用户及其位置

这是常见的情况,并且被广泛使用。例如:

<%= form_for @user, users_path do |form| %>
 <%= form.text_field :name %>
 <%= form.fields_for :locations do |f| %>
   <%= f.text_field :location %>
     ...
 <% end %>
<%= form.submit %>
<% end %>

你应该阅读:http://api.rubyonrails.org/关于ActiveRecord :: NestedAttributes :: ClassMethods