我有一个Message
模型,在我的Rails 4应用中有archived
个参数。在展示视图中,我有button_to
将archived
参数设置为true
。在我将Devise和Mailer添加到Message
模型之前,此函数之前已有效。现在,当我点击"存档"按钮,我得到一个" ActionController :: InvalidAuthenticityToken"错误。我发现唯一可以避免此错误的是将skip_before_filter :verify_authenticity_token, :only => [:archive]
添加到我的Messages Controller
。但是,当我这样做时,它并没有挽救这些参数。
有没有办法通过button_to链接传递真实性令牌?或者有没有更好的方法来实现这一点并不会损害它的安全性?
Message.rb
class Message < ActiveRecord::Base
validates_presence_of :name, :email, :message
has_one :response
scope :unread, -> { where(viewed: nil)}
scope :viewed, -> { where(viewed: true)}
scope :inbox, -> { where(archived: nil)}
scope :archived, -> { where(archived: true)}
end
Messagescontroller.rb
class MessagesController < ApplicationController
include MessagesHelper
before_action :authenticate_admin!, :except => [:new]
def index
@viewed = Message.viewed
@unread = Message.unread
end
def new
@message = Message.new
end
def create
@message = Message.new(message_params)
if @message.save(message_params)
Messagemailer.message_created(@message).deliver_now
redirect_to root_path
flash.notice = "Message succesfully sent."
else
render "new"
flash.alert = "There was a problem sending your message: "
flash.alert += @message.errors.full_messages.join(", ")
end
end
def edit
@message = Message.find(params[:id])
end
def update
@message = Message.find(params[:id])
if @message.update(message_params)
redirect_to message_path(@message)
flash.notice = "Message succesfully sent."
else
render "edit"
flash.alert = "There was a problem updating the message: "
flash.alert += @message.errors.full_messages.join(", ")
end
end
def view
@message = Message.find(params[:id])
@message.viewed = true
if @message.save
redirect_to message_path(@message)
else
flash.alert = "There was a problem viewing the message"
end
end
def unview
@message = Message.find(params[:id])
@message.viewed = nil
if @message.save
redirect_to messages_path
else
flash.alert = "There was a problem un-viewing the message"
end
end
def show
@message = Message.find(params[:id])
end
def archive
@message = Message.find(params[:id])
if @message.save(:archived => true)
redirect_to messages_path
else
flash.alert = "There was a problem archiving the message"
render :show
end
end
end
MessagesHelper.rb
module MessagesHelper
def message_params
params.require(:message).permit(:name, :email, :subject, :message, :viewed, :responded, :archived)
end
end
消息显示按钮
<%= button_to 'Archive', message_archive_path(@message), :class => 'button' %></div>
任何帮助表示赞赏!谢谢!
编辑:
这显然也适用于我的所有形式。这是一个设计问题吗?