嵌套表单:如何设置子资源的用户ID?

时间:2012-08-25 21:46:30

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

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

User.rb

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

Location.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

Rate.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

LocationsController

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

1 个答案:

答案 0 :(得分:1)

关于这个主题有一个很好的轨道广播;剧集196和197.更好的是,瑞恩写了一个宝石https://github.com/ryanb/nested_form

宝石非常容易实现。如果设置正确,嵌套表单将自动创建父对象ID。

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