2012-08-03 51 views
1

我在我的Rails 3應用程序中有一個簡單的建議模型。我試圖在索引視圖上添加一個簡單的link_to鏈接,點擊時將該建議標記爲已批准。創建操作以更改Rails 3中的布爾值

到目前爲止,我有以下代碼:

的routes.rb

resources :suggestions do 
get :approve 
end 

suggestions_controller.rb

def approve 
@suggestion = Suggestion.find(params[:id]) 
@suggestion.update_attribute(:approved, 'true') 
@suggestion.update_attribute(:approved_on, Time.now) 
redirect_to suggestion_path 
end 

suggestion.rb

attr_accessible :author, :details, :localip, :title, :approved, :approved_on 

schema.rb

create_table "suggestions", :force => true do |t| 
t.string "title" 
t.string "author" 
t.text  "details" 
t.string "localip" 
t.datetime "created_at",      :null => false 
t.datetime "updated_at",      :null => false 
t.boolean "approved", :default => false 
t.datetime "approved_on" 
end 

index.html.erb(建議)

<% if @suggestion.approved? %> 
    <%= @suggestion.approved_on %> 
<% else %> 
    Not yet approved. (<%= link_to "Approve", approve_suggestion_url(@approve), :method => :put %>) 
<% end %> 

當使用上述代碼時,得到下面的異常錯誤:

undefined method `approved?' for nil:NilClass 

我錯過了某個地方的某個步驟嗎?

回答

1

最可能的是,你已經發布的代碼是內部的像

<% @suggestions.each do |suggestion| %> 
    ... 
    <% if @suggestion.approved? %> 
    <%= @suggestion.approved_on %> 
    <% else %> 
    Not yet approved. (<%= link_to "Approve", approve_suggestion_url(@approve), :method => :put %>) 
    <% end %> 
<% end %> 

您需要使用suggestion變量,而不是@suggestion實例變量每次循環。此外,要構建建議批准網址,您需要使用suggestion而不是@approve。代碼應該像

<% if suggestion.approved? %> 
    <%= suggestion.approved_on %> 
    <% else %> 
    Not yet approved. (<%= link_to "Approve", approve_suggestion_url(suggestion), :method => :put %>) 
    <% end %> 

此外,你應該修改你的routes.rb以反映approve行動是其成員的行動。

resources :suggestions do 
    put :approve, on: :member 
end 

要了解會員和收集路線之間的區別,請閱讀difference between collection route and member route in ruby on rails?

+0

啊,謝謝,愚蠢的錯誤!我似乎得到了一個路由錯誤,雖然'沒有路由匹配[PUT]「/ suggestions/8/approve」' – dannymcc 2012-08-03 13:27:23

+0

如果你想保持鏈接生成的方法,然後修改routes.rb爲'put:approve,on: :member'。 – 2012-08-03 13:28:39

+0

明白了,謝謝! – dannymcc 2012-08-03 13:45:08