我有一张场地和优惠表。每个场地都有很多优惠。
我希望能够从场地编辑页面向场地添加优惠。到目前为止,我有这个(下面的代码),但它给出了“场地中的NoMethodError#edit,未定义的方法`model_name',用于NilClass:Class”错误。
场地编辑页面 (div id =“tabs-3”是手风琴中的容器)
<div id="tabs-3">
<%= form_for [@venue, @offer] do |f| %>
<h2 class="venue_show_orange">Offers</h2>
<%= f.fields_for :offers do |offer| %>
<div class="add_offer">
<%= offer.text_field :title %><br>
</div>
<div class="button"><%= submit_tag %></div>
<% end %>
<% end %>
</div>
提供控制器
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 offers_path
else
render :action => :new
end
end
def edit
@offer = Offer.find(params[:id])
end
def update
@offer = Offer.find(params[:id])
@offer.attributes = params[:offer]
if @offer.save!
flash[:notice] = 'Offer updated successfully'
redirect_to offers_path(@offer)
end
end
end
场地控制器 (这里没有任何相关的报价 - 这是我出错的地方吗?)
class VenuesController < ApplicationController
protect_from_forgery :only => [:update, :delete, :create]
load_and_authorize_resource
def new
@venue = Venue.new
5.times { @venue.venuephotos.build }
end
def create
@venue = Venue.new params[:venue]
if @venue.save
flash[:notice] = 'Venue added'
redirect_to venues_path
else
render :action => :new
end
end
def edit
@venue = Venue.find(params[:id])
5.times { @venue.venuephotos.build }
end
def update
@venue = Venue.find(params[:id])
@venue.attributes = params[:venue]
if @venue.save!
flash[:notice] = 'Venue updated successfully'
redirect_to :back
end
end
end
非常感谢任何帮助!
修改
场地编辑页面
<div id="tabs-3">
<%= form_for @venue do |f| %>
<div class="edit_venue_details">
<h2 class="venue_show_orange">Offers</h2>
<%= render :partial => 'offers/offer', :collection => @venue.offers %>
<div class="clearall"></div>
<h2 class="edit_venue_sub_header">Add a new offer</h2>
<%= f.fields_for :offers do |offer| %>
<% if offer.object.new_record? %>
<p class="edit_venue">title: <br>
<%= offer.text_field :title, :class => "edit_venue_input" %></p>
<% end %>
<% end %>
</div>
<button class="submit_button" type="submit"> Save changes</button>
<% end %>
</div>
显示什么
但是,如果我添加新优惠,则会正确显示:
答案 0 :(得分:2)
一些评论:
1)替换:
<%= form_for [@venue, @offer] do |f| %>
使用:
<%= form_for @venue do |f| %>
由于offers
数据将通过相关venue
更新,因此只有一个控制器操作可以处理该表单。
2)如果你想在这个表单中添加一些不存在的offers
,你应该按照venuephotos
3)显示您的Venue
模型。你应该至少:
accepts_nested_attributes_for :offers
答案 1 :(得分:1)
修正:
<%= f.fields_for :offers, @venue.offers.build do |offer| %>