【发布时间】:2020-02-23 14:34:51
【问题描述】:
我觉得这是一个直截了当的问题,但似乎没有其他推荐的解决方案有效。基本上,我想要的只是一个应用程序,它可以使用属性电话号码创建订阅者。
订阅者控制器
class SubscribersController < ApplicationController
def index
end
def new
@subscriber = Subscriber.new
end
def create
@subscriber = Subscriber.new(subscriber_params)
@subscriber.save
end
def show
@subscribers = Subscriber.all
end
def update
end
private
def subscriber_params
params.require(:subscriber).permit(:phone)
end
end
创建.html.erb
<div class="recent">
<h3>Subscribe to Texts</h3>
<%= form_for @subscriber do |f| %>
<span><label for="phone">Phone</label></span>
<%= f.text_field :phone, class: 'form-control' %>
<%= f.submit %>
<%end%>
</div>
<% [:success, :error].each do |key| %>
<% if flash[key] %>
<div class="<%= key %>" id="flash">
<%= flash[key] %>
</div>
<% end %>
<% end %>
如果我取出 .require(:subscriber) 它不会保存订阅者,它会创建一个回滚事务,说明订阅者是一个未经许可的参数
如果我将订阅者放在 .permit 下,它就不会通过表单保存它。
我该怎么办?我觉得这是直截了当的,这使得它更加令人沮丧。
编辑:如果我将它放在 .permit(:subscriber, :phone) 下,该程序将无法使用 .require(:subscriber) 运行,我会在服务器日志中得到它
参数:{"utf8"=>"✓", "authenticity_token"=>"xxxx==", "subscriber"=>{"phone"=>"5555555555"}, "commit"=>"创建订阅者"} 不允许的参数::utf8, :authenticity_token, :subscriber, :commit
如果我只是输入 .permit(:phone) 我会得到同样的结果
如果我输入@subscriber.save!在创建方法中我得到这个错误:
app/controllers/subscribers_controller.rb:20:in `subscriber_params'
app/controllers/subscribers_controller.rb:6:in `create'
Started GET "/" for ::1 at 2020-02-23 10:02:32 -0500
Processing by SubscribersController#create as HTML
(0.2ms) begin transaction
(0.1ms) rollback transaction
Completed 422 Unprocessable Entity in 11ms (ActiveRecord: 0.9ms)
ActiveRecord::RecordInvalid (Validation failed: Phone can't be blank):
app/controllers/subscribers_controller.rb:7:in `create'
【问题讨论】:
-
那么到底是什么问题?您想在没有
:subscriber参数的情况下保存记录吗?有点不清楚您到底遇到了什么问题。当您尝试按原样保存带有代码的记录时会发生什么?发布一个正在发送的参数示例也可能会有所帮助,我们可能需要它来帮助您。 -
我想创建一个新的订阅者,如果我按原样发出代码,它会给我错误 ActionController::ParameterMissing in SubscribersController#create 并且不显示主页
-
好的,你能把正在发送的参数贴出来吗,你提交表单时应该可以在控制台中看到它们
-
是的,所以即使运行程序我也需要取出 .require(:subscriber) 然后我会得到参数:{“xxxx”=>“✓”,“authenticity_token”=> "xxxxx==", "subscriber"=>{"phone"=>"5555555555"}, "commit"=>"Create Subscriber"} 不允许的参数::utf8, :authenticity_token, :subscriber, :commit (0.1ms)开始事务(0.1ms)回滚事务如果我放.permit(:subscriber,:phone),我得到几乎相同的东西但是:“subscriber”=>{“phone”=>“8884848999”}
-
是的,你的控制器搞砸了。您需要一个带有
@subscriber = Subcriber.new的新操作,并且该新操作显示表单,当您点击保存时,create 方法使用post创建记录。你的问题是你永远没有新的记录可以使用
标签: ruby-on-rails