accepts_nested_attributes_for 在 Rails 3 中的实际使用形式 [英] accepts_nested_attributes_for practical form use for in Rails 3
问题描述
使用 Ruby on Rails 3:
Using Ruby on Rails 3:
我不太了解 accepts_nested_attributes_for 是如何应该工作的,但我想不出一种实用的方法来在表单中实现它.例如,如果有人想在他们的用户页面中添加他们最近的位置:
I semi-understand how accepts_nested_attributes_for is supposed to work, but I can't figure out a practical way to implement this in a form. For example, if someone wanted to add their most recent locations in their user page:
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
中实际实现这一点的任何想法?文档没有讨论任何关于视图的内容.
Any ideas on how I go about implementing this practically in the user view _form.html.erb
? The documentation doesn't talk anything about the view whatsoever.
我尝试使用 railscast 教程,但它没有任何效果——我相信该演员表是为 rails 2.3 制作的,但我不确定 3 中是否有不同的用法.
I tried using the railscast tutorial but it did not work whatsoever -- I believe the cast was made for rails 2.3, but I'm not sure if there's different usage in 3.
推荐答案
accepts_nested_attributes 需要实现的情况,当你有一些链接的模型并希望以一种形式创建和编辑它们.
例如:用户及其位置
accepts_nested_attributes need to implement situation when you have some chained models and want to create and edit them in one form.
For example: Users and their Locations
这是很常见的情况,并且被广泛使用.例如:
This is common situation and it's used widely. For example:
<%= 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::类方法
You should read: http://api.rubyonrails.org/ about ActiveRecord::NestedAttributes::ClassMethods
这篇关于accepts_nested_attributes_for 在 Rails 3 中的实际使用形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!