0

Userに保存しようとしていRateます。プレゼンス検証を削除することでレートに保存することができましたが、Location作成後に現在のユーザーがありません。ネストされたフォームでこれを行うにはどうすればよいですか?

ユーザー.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

ロケーションコントローラー

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

gem の実装は非常に簡単です。正しく設定されている場合、ネストされたフォームは、作成時に親オブジェクト ID を自動的に取得します。

あなたが投稿したコードに間違っているものは何もありません...ネストされたフォームはビューでどのように見えますか?

于 2012-08-25T22:55:40.497 に答える