我试图让我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 %>