我有一个Coupons
有两个动作的控制器。
class CouponsController < ApplicationController
filter_resource_access
def index
@coupons = Coupon.all
end
#generates 10 new coupons on each call
def generate
plan_id = params[:plan_id]
numdays = params[:num_days]
(1..10).each do |i|
validChars = %w{ 1 2 3 4 5 6 7 9 a A b B d D e E f g G h H j J k K m M n N p P q Q r R t T }.to_a
code = (0...6).map{ validChars[ rand(validChars.size) ] }.join
coupon = Coupon.new
coupon.code = code
coupon.plan_id = plan_id
coupon.active = false
coupon.subdays = numdays
coupon.save
end
redirect_to :coupons_path
end
end
在我的视图中调用生成操作,如下所示:
<h2 class="page-title">Coupons</h2>
<div class="main">
<%= form_tag "coupons/generate" do -%>
<%= hidden_field_tag 'user[plan_id]', "1" %>
<%= hidden_field_tag 'user[num_days]', "150" %>
<%= submit_tag "Generate 10 Coupons!", :class => "primary button" %>
<% end -%>
<table border="0" class="list">
<thead>
<tr>
<th>Code</th><th>Plan</th><th>Duration</th><th>Activated</th>
</tr>
</thead>
<tbody>
<% if !@coupons.nil? %>
<% @coupons.each do |coupon| %>
<tr class="<%#= list_entry or list_entry_alt %>">
<td><%= coupon.code %></td>
<td><%= coupon.plan_id %></td>
<td><%= coupon.subdays %> days</td>
<td><% if coupon.started.nil? == true %>
<%= 'Not yet' %>
<% else %>
<%= time_ago_or_time_stamp coupon.started %>
<% end %>
</td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
</div>
我的config/authorization_rules.rb
样子是这样的:
has_permission_on [:coupons], :to => [:index, :show, :step, :new, :create, :edit, :update, :destroy, :generate]
以上所有抛出的错误都是这样的:
filter_access_to tried to find Coupon from params[:id] (nil), because attribute_check is enabled and @coupon isn't set, but failed: ActiveRecord::RecordNotFound: Couldn't find Coupon without an ID
Completed 404 Not Found in 245ms
ActiveRecord::RecordNotFound (Couldn't find Coupon without an ID):
但是,一旦我将其更改filter_resource_access
为filter_access_to :all, :except => :generate
它就不会再给我错误并且有点工作。
即它会生成一些我正在寻找的优惠券代码,但它不包括视图输出中的plan_id 编号或天数。
这是为什么?我究竟做错了什么?
编辑1:顺便说一句,它确实限制了正确的人......即只有指定的角色才能查看coupons index view
. 所以过滤器部分起作用。