我有一个模特:
class Message < ActiveRecord::Base
attr_accessible :topic, :body, :completeDate, :created_at
belongs_to :account
belongs_to :user
has_many :message_followups
end
我有一个控制器:
class MessagesController < ApplicationController
def close
@message = Message.find(params[:messageId])
@message.completeDate = Date.today
if @message.save
redirect_to myHomeMessages_path, :flash => { :success => "Your message was closed." }
else
redirect_to myHomeMessages_path, :flash => { :error => "Error closing message." }
end
end
end
我有一个观点:
<%= form_for (???) do |f| %>
Are you sure you wish to close this message?<br>
<%= hidden_field_tag 'messageId', message.id.to_s %>
<%= submit_tag "Close Message" %>
<% end %>
我在弄清楚如何获取form_for或form_tag以在消息控制器中调用特定方法'close'时遇到问题。非常感谢任何帮助,谢谢。
马特
答案 0 :(得分:6)
一个非常重要的提示,你不应该在Ruby上使用camel case作为变量名,变量sand方法应该使用下划线作为分隔符,如果你来自另一种语言,如Java,尽量避免使用您在那里使用的相同命名模式。 ruby中的Camel case仅适用于类和模块名称。
我猜你正在使用Ruby on Rails 3,因为你没有说过你正在使用的东西。首先,你需要一个路由,它在routes.rb文件中看起来像这样:
resources :messages do
member do
post 'close'
end
end
对控制器稍作修改
def close
@message = Message.find(params[:id]) #you don't need to use the hidden field here
@message.completeDate = Date.today
if @message.save
redirect_to myHomeMessages_path, :flash => { :success => "Your message was closed." }
else
redirect_to myHomeMessages_path, :flash => { :error => "Error closing message." }
end
end
你的表格看起来像这样:
<%= form_for( @message, :url => close_message_path( @message ), :html => { :method => :post } ) do |f| %>
Are you sure you wish to close this message?<br>
<%= f.submit "Close Message" %>
<% end %>
此表单将发布到“/ messages / ID_HERE / close”,Rails将在您的请求中将“ID_HERE”值设置为“id”参数。
答案 1 :(得分:2)
这样的事情应该为你解决问题:
<%= form_for @message, :url => { :action => "close" }, :html => { :method => :put } do |f| %>
这样做是指定您正在对消息控制器中的close
方法执行HTTP PUT方法。有关form_for
辅助方法的详细信息,请阅读here
答案 2 :(得分:0)
你的控制器中是否有更新方法,如果没有,你可以这样做:
<%= form_for( @message ) do |f|
<p>Are you sure you wish to close this message?</p>
<%= hidden_field_tag :close %>
<%= f.submit "Close Message" %>
<% end %>
然后在你的控制器中:
class MessagesController < ApplicationController
def update
@message = Message.find(params[:id])
@message.completeDate = Date.today if params.has_key?(:close)
if @message.save
redirect_to myHomeMessages_path,
:flash => { :success => "Your message was closed." }
else
redirect_to myHomeMessages_path,
:flash => { :error => "Error closing message." }
end
end
end