2
我讀過很多關於這個問題的文章,但我從來沒有得到這個工作。Ruby on Rails - f.error_messages沒有顯示出來
我的模型看起來是這樣的:
class Announcement < ActiveRecord::Base
validates_presence_of :title, :description
end
我控制器的創建方法(僅其相關部分)如下:
def create
respond_to do |format|
if @announcement.save
flash[:notice] = 'Announcement was successfully created.'
format.html { redirect_to(@announcement) }
format.xml { render :xml => @announcement, :status => :created, :location => @announcement }
else
@announcement = Announcement.new
@provinces = Province.all
@types = AnnouncementType.all
@categories = Tag.find_by_sql 'select * from tags where parent_id=0 order by name asc'
@subcategories= ''
format.html { render :action => "new" } #new_announcement_path
format.xml { render :xml => @announcement.errors, :status => :unprocessable_entity }
end
end
end
我的形式如下:
<% form_for(@announcement) do |f| %>
<%= error_messages_for 'announcement' %> <!--I've also treid f.error_messages-->
...
我在做什麼錯?
你說得對。這是問題所在。你知道我爲什麼在渲染之前將這些行放入else狀態嗎?因爲我有需要用這些變量初始化的組合框(我在「new」方法中創建它們),並且如果我沒有將它們放在else子句中,它將引發異常。你能告訴我如何重用這些線路以避免在任何地方重複它們?謝謝! – 2010-04-28 17:39:53
只需在控制器中創建一個專用功能,以設置變量並在需要時調用該功能。 – 2010-04-28 17:50:05
謝謝!現在它可以工作。 – 2010-04-28 18:01:51