0

我是 Rails 新手,我正在尝试创建一个简单的书签表:

  def up
create_table :bookmarks do |t|
    t.string  :path,        :null => false
    t.integer :user_id,     :null => false

    t.timestamps
end

add_index :bookmarks, :user_id
add_index :bookmarks, :path
  end

然后我在我的控制器中有这个:

    # GET bookmark/new
# GET bookmark/new.json
def new
    @bookmark = Bookmark.new
end

# POST bookmark/new
# POST bookmark/new.json
def create
    @bookmark = Bookmark.new(params[:bookmark])
    if @bookmark.save
        flash[:success] = "Bookmark Saved"
    else
        flash[:failure] = "Failed !"
    end
end

我的观点是:

<%= form_for :bookmark do |bookmark| %>
<%= bookmark.label :path %>
<%= bookmark.text_field :path %>

<%= bookmark.label :user_id %>
<%= bookmark.text_field :user_id %>

<%= bookmark.submit "Add bookmark" %>
<% end %>

最后运行 rake routes 得到这个路由列表:

          bookmark_index GET    /bookmark(.:format)            bookmark#index
                     POST   /bookmark(.:format)            bookmark#create
        new_bookmark GET    /bookmark/new(.:format)        bookmark#new
       edit_bookmark GET    /bookmark/:id/edit(.:format)   bookmark#edit
            bookmark GET    /bookmark/:id(.:format)        bookmark#show
                     PUT    /bookmark/:id(.:format)        bookmark#update
                     DELETE /bookmark/:id(.:format)        bookmark#destroy

当我尝试提交表单时,我收到此错误:

Routing Error

No route matches [POST] "/bookmark/new"

Try running rake routes for more information on available routes. 

编辑:

将 :bookmark 更改为 @bookmark 会引发此错误:

    NoMethodError in Bookmark#new

Showing /media/wahtver/600415AD27D78282/3pces/pces/app/views/shared/_bookmark_form.html.erb where line #1 raised:

undefined method `bookmarks_path' for #<#<Class:0x00000003a48398>:0x007f1034b6b908>

Extracted source (around line #1):

1: <%= form_for @bookmark do |bookmark| %>
2:  <%= bookmark.label :path %>
3:  <%= bookmark.text_field :path %>
4: 

问题是什么?

谢谢

4

2 回答 2

1
<%= form_for @bookmark do |bookmark| %>

并不是

<%= form_for :bookmark do |bookmark| %>

更仔细地查看错误消息。它正在使用POST,而不是GET

编辑:您的路线应该是resources :bookmarks.

当你运行rake routes它应该给你:

bookmarks GET /bookmarks(.:format) bookmarks#index

于 2013-03-16T14:38:58.307 回答
0

你是如何声明你的路线的?你有你的 route.rb 文件resource :bookmarkresources :bookmarks

如果你在你的 create 方法中看到你的控制器,你有这个:

# POST bookmark/new
# POST bookmark/new.json
def create

注意使用脚手架时rails在每个方法上方自动生成的注释(我猜你是用脚手架生成的控制器),它应该是POST /bookmarksPOST /bookmark。如果您出于某种原因使用脚手架,那么轨道会生成错误的路线。

显示您的routes.rb文件。

于 2013-03-16T15:07:01.620 回答