我遇到了一个不可能那么复杂的问题,但我只是没有把事情做好。
假设我有两个模型:
class Notification < ActiveRecord::Base
belongs_to :device
validates :number, presence: true
end
和
class Device < ActiveRecord::Base
belongs_to :user
has_many :notifications, :dependent => :destroy
//rest omitted for brevity
end
使用嵌套路由,如下所示:
resources :devices do
resources :notifications
end
和一个像这样的通知 Controller :
class NotificationsController < ApplicationController
before_filter :authenticate_user!
before_action :set_device, :only => [:index, :new, :create]
before_filter :load_notification, only: :create
load_and_authorize_resource :device
load_and_authorize_resource :notification, :through => :device
def index
end
def new
@notification = @device.notifications.build
end
def create
params.each do |param|
logger.debug param
end
@notification = @device.notifications.build(notification_params)
if @notification.save
redirect_to [@notification.device, @notifications], notice: 'Notification was successfully created.'
else
render action: 'new'
end
end
private
def load_notification
@notification = Notification.new(notification_params)
end
def set_device
@device = Device.find(params[:device_id])
end
def notification_params
params.fetch(:notification, {}).permit(:number, :device_id, :message)
end
end
现在说到创建通知:
表单按方面工作。但是:我想实现第二个目标。
通知应该可以重新发送,所以我在通知索引 View 中有这个:
<%= link_to 'Resend', device_notifications_path(number: notification.number, message: notification.message), :method => :post %>
但是验证失败,我重定向到新页面,没有任何预填充的字段告诉我需要数字,所以肯定缺少一些我不明白的明显内容。
请求中的参数:
[["user_id", xyz]]
["_method", "post"]
["authenticity_token", "myauthenticitytokenstring"]
["number", "+1555123456789"]
["action", "create"]
["controller", "notifications"]
["device_id", "9"]
["notification", {}]
(不需要留言)
我认为错误在于 Controller 中的 notification_params 方法。
任何人都可以帮助我吗?
最佳答案
我刚才遇到了类似的问题,这对我有用:
<%= link_to 'Resend', device_notifications_path(@notification.device_id, notification: { number: notification.number, message: notification.message }), :method => :post %>
基本上,您需要将 Controller /模型数据包装到 Controller 参数的哈希中。这就是 Controller 本身读取它的方式。另外,您是否没有在
device_id
中遗漏 device_notifications_path
?[["user_id", xyz]]
["_method", "post"]
["authenticity_token", "myauthenticitytokenstring"]
["action", "create"]
["controller", "notifications"]
["device_id", "9"]
["notification", {["number", "+1555123456789"]}]
现在,我只是假设
device_id
位于您的 URL 路由中:http:\\localhost:3000\notifications\9
这就是为什么
device_id
不必在哈希本身中的原因。这只是基于我在这里的假设,没有更多的 view
和 routes
继续下去。总而言之,它确实与哈希有关。稍微玩一下,然后使用 p
将 development.log 中的数据打印出来进行测试:def create
p params
p notification_params
...
end
此外,可选但不是必需的,您可以使用
.require
而不是 .fetch
来干燥 Controller 的参数 def ,如下所示:private
def notification_params
params.require(:notification).permit(:number, :device_id, :message)
end
关于http-post - 带有 link_to 的 rails 4 和带有强参数的方法 post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18248304/