2011-02-01 81 views
2

我使用了form_tag從一個Rails視圖中的不同控制器訪問一個動作。這給我渲染錯誤信息造成了麻煩。我也在使用可能會導致問題的JQuery。我讀過form_tag沒有綁定到模型,所以這可能意味着像validates_uniqueness_of這樣的東西可能無法正常工作。希望有助於理解與form_tag驗證!帶單獨控制器中的form_tag的錯誤消息Rails 3

供參考,這是我的控制器:

 
# app/controllers/posts_controller.rb 
def create 
    @post = Post.new 
    @post.text = params[:text] 
    @post.user_id = current_user.id 
    @post.save 

    respond_to do |format| 
    if @post.save 
     format.js 
     format.html { redirect_to(username_path(:username => current_user)) } 
     format.xml { render :xml => @post, :status => :created, :location => @post } 
    else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @post.errors, :status => :unprocessable_entity } 
    end 
    end 
end 

而且我認爲(在我的用戶模型)

  
# app/views/users/show.html 
<% form_tag({:controller => "posts", :action => "create"}, :method => "post", :class => 'newpost') do %> 
    <%= error_messages_for :post %> 
    <%= text_field_tag :text, params[:text] %> 
    <%= image_submit_tag("../images/add.png", :border => 0, :class => "submitadd") %> 
%lt;% end %> 
+0

你有什麼問題? – 2011-02-01 02:50:54

+0

服務器輸出顯示消息發佈,但是沒有錯誤消息正在返回。當輸入與驗證匹配時,該帖子可以工作,但瀏覽器中不會發生任何事情。 – James 2011-02-01 03:06:21

回答

2

我認爲這個問題是可能是你是雙儲蓄和不知何故清除一些錯誤消息。你可以嘗試,而不是執行以下操作:

 
# app/controllers/posts_controller.rb 
def create 
    @post = Post.new 
    @post.text = params[:text] 
    @post.user_id = current_user.id 

    respond_to do |format| 
    if @post.save 
     format.js 
     format.html { redirect_to(username_path(:username => current_user)) } 
     format.xml { render :xml => @post, :status => :created, :location => @post } 
    else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @post.errors, :status => :unprocessable_entity } 
    end 
    end 
end 

調用render後:動作=>「新」你應該能夠查看錯誤信息:

 
<%= error_messages_for @post %> 

您可以驗證是否有通過有錯誤在日誌中也顯示@ post.errors。