0

我试图让我User保存到Rate. 我可以Location通过删除存在验证来将其保存到 Rate 中,但是在它创建之后它没有当前用户。我将如何为我的嵌套表单执行此操作?

用户.rb

attr_accessible :email, :password
has_many :locations
has_many :rates

位置.rb

attr_accessible :name, :rates_attributes
belongs_to :user
has_many :rates
accepts_nested_attributes_for :rates, :reject_if => :all_blank
# Not sure if :all_blank works anyways as it - 
# still saves even when theirs no user_id, lol

比率.rb

attr_accessible :amount, :location_id
belongs_to :location
belongs_to :user
validates_presence_of :amount
# Couldn't use these validations
# validates_presence_of :user_id 
# validates_presence_of :location_id

位置控制器

def new
  @location = Location.new
  @location.rates.build
end

def create
  @location = current_user.locations.build(params[:location])
  if @location.save.....
end

位置/new.html.erb

<%= nested_form_for @location do |f| %>
  <%= f.label :name, "Name *" %>
  <%= f.text_field :name  %>

  <%= f.link_to_add "Add Rate", :rates %>
  <%= f.fields_for :rates do |r| %>
    <%= r.text_field :amount %>
    <%= r.link_to_remove "Remove" %>
  <% end %>
  <%= f.submit "Add Location" %>
<% end %>
4

1 回答 1

1

关于这个主题有一个很棒的 railscast;第 196 和 197 集。更好的是,Ryan 写了一个 gem https://github.com/ryanb/nested_form

gem 非常容易实现。如果设置正确,嵌套表单会在创建时自动获取父对象 ID。

我没有注意到您发布的代码中有任何看起来错误的内容......您的嵌套表单在视图中是什么样的?

于 2012-08-25T22:55:40.497 回答