1

我的 Rails 3 应用程序中有一个简单的建议模型。我正在尝试在索引视图上添加一个简单的 link_to 链接,单击该链接将建议标记为已批准。

到目前为止,我有以下代码:

路线.rb

resources :suggestions do
 get :approve
end

建议控制器.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

建议.rb

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

架构.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

我错过了某个地方的一步吗?

4

1 回答 1

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实例变量。此外,要构建建议批准 url,您需要使用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

要了解成员和收集路线之间的区别,请阅读ruby​​ on rails 中收集路线和成员路线之间的区别?.

于 2012-08-03T13:19:20.490 回答