开发者

accepts_nested_attributes_for practical form use for in Rails 3

Using Ruby on Rails 3:

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 table

location
  -location
  -length_of_stay
  -user_id

Any ideas on how I go about implementing this practically in the user view _form.html.erb? The documenta开发者_运维知识库tion doesn't talk anything about the view whatsoever.

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 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 %>

You should read: http://api.rubyonrails.org/ about ActiveRecord::NestedAttributes::ClassMethods

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜