2015-11-24 29 views
1

我越來越想在我的Rails應用程序的form_for使用時出現以下錯誤:未定義的方法 'TO_KEY' 錯誤使用的form_for

undefined method `to_key' for #<Table::ActiveRecord_Relation:0x8a09ca8> 

我的config/routes.rb文件是:

root 'welcome#index' 
post 'foo', as: 'foo', to: 'welcome#index' 

的控制器是:

class WelcomeController < ApplicationController 

    def index 
     @tables = Table.all 
    end 

    def test 
     @tables = Table.all 
    end 

end 

和歡迎/ index.html.erb的看法是:

<p> 
    <%= form_for @tables, :url => foo_path do |t| %> 
    <%= t.text_area :name %> 
    <% end %> 
</p> 

我試過做文檔中建議的url解決方法,但我仍然得到相同的錯誤。

有誰知道我在做什麼錯?我想更多地瞭解這個bug,以便我可以更好地處理它。

+1

以rails開頭請參閱此http://guides.rubyonrails.org/getting_started.html –

回答

1

根據您的代碼,index正在返回一個集合。但是你的觀點試圖爲它定義一個表單。這不太可能會成功。

表單用於對象,不用於集合。

也許你可以這樣做

def new 
    @table = Table.new 
end 

new.html.erb

<%= form_for @table do |f| %> 
    ... 
<% end %> 

如果你想堅持用index.html.erb與形式。然後,您必須編輯您的路線索引行動,並在控制器中它應該是爲創建一個新的對象。

def index 
    @table = Table.new 
end 

希望它有幫助!

+0

我在索引操作中調用了Table.new,它起作用!現在對我來說很有意義。使用Table.all傳遞form_for對象的集合,這不起作用,但使用Table.new正確地將它傳遞給單個對象。相反,我期待在像Table.new這樣的東西上使用像.each這樣的方法也不行。謝謝! –

0

我看到你的代碼有3個不正確的東西
作爲RESFUL標準則:

  • 指數動作總是取得動作都要經過這樣的路由文件應定義再次相同的是:
    root "wellcome#index" get "foo", to: "wellcome#index", as: :foo

  • form_for通常與模型對象一起使用,但在您使用@tables時不會收集,如果模型對象未保存到數據庫中form_for使用創建1個對象到數據庫,否則form_for使用更新該對象

  • ,如果你想創建的索引操作的形式,你可以跟着我:
    def index @tables = Table.all @table = Table.new end
    index.html.erb文件
    <%= form_for @table do |f| %> <%= f.label :name %>
    <%= f.text_field :name %>
    <%= f.submit %> <% end %>

    你需要創建tables_controller處理來自表單請求發送給服務器。你運行:
    rails g controller tables 在table_controller.rb中你寫成: def create @table = Table.new table_params if @table.save redirect_to root_path, notice: "success" else redirect_to root_path, alert: "fail" end end

private def table_params params.require(:table).permit :name end 這樣。結束。祝你一天愉快!

相關問題