如何从其他记录编辑页面添加关联记录?

时间:2011-07-18 18:51:39

标签: ruby-on-rails associations record

我是编程和rails的新手。我有一张场地桌和一张优惠表。一个场地可以提供许多优惠,并且优惠属于一个场地。

我希望能够在场馆edit.html.erb页面上为场地添加优惠。我怎样才能做到这一点?我认为我已经使用的代码可以工作,但它不会保存任何内容而不会出现任何错误。

场地模型

class Venue < ActiveRecord::Base
  has_many :offers
end

提供型号

class Offer < ActiveRecord::Base
  belongs_to :venue
end

场地管制员

  def edit
    @venue = Venue.find(params[:id])    
    @offer = Offer.new
  end

提供控制器

class OffersController < ApplicationController

  def new
    @offer = Offer.new
  end

  def create
    @offer = @venue.offers.create!(params[:offer])
    @offer.venue = @venue
    if @offer.save
      flash[:notice] = 'Offer added'
      redirect_to :back
    else
      render :action => :new
    end
  end
end

场地edit.html.erb

<div id="tabs-3">
  <%= form_for @venue do |f| %>
    <div class="edit_venue_details">

      <h2 class="edit_venue_header">Offers</h2>

      <% if @venue.offers.count.zero? %>
        <div class="no_offers">
          No offers added yet.
        </div>
      <% else %>
        <%= render :partial => 'offers/offer', :collection => @venue.offers %>
      <% end %>    
      <div class="clearall"></div>
    </div>

    <h2 class="edit_venue_sub_header">Add a new offer</h2>

    <%= form_for @offer do |offer| %>
      <p class="edit_venue">title: <br>
      <%= offer.text_field :title, :class => "edit_venue_input" %></p>
      <button class="submit_button" type="submit"> Save changes</button>
    <% end %>
  <% end %>
</div>

感谢任何帮助,非常感谢!

1 个答案:

答案 0 :(得分:1)

您将使用Rails的概念o 嵌套属性和form.fields_for方法。 See docs.

在你的情况下,它应该是这样的:

<强>模型

class Venue < ActiveRecord::Base
  has_many :offers
  accepts_nested_attributes_for :offers
end

查看

...
<%= f.fields_for :venues, @venue.offers.new do |offer_fields| %>
  <%= offer_fields.text_field :title %>
<% end %>
...