我目前正试图限制用户每月可以发布的帖子数量。但是,我似乎无法让视图认识到后配额方法位于 post.rb 模型文件中。我尝试了一些不同的方法,但代码继续抛出错误。如何在达到帖子限制之前获取后配额方法?错误和代码如下。
错误
undefined method `user_basic_post_quota?' for #<Post:0xac6a730>
post.rb
def self.user_basic_post_quota?
if current_user.subscription_plan.stripe_id == 1 && current_user.posts.where(:created_at => (Time.zone.now.beginning_of_month..Time.zone.now)).count >= 200
errors.add(:base, "Exceeded The Amount of Posts That You Can Create For Your Account!")
end
end
发布_form.html.erb
<%= simple_form_for(@post) do |f| %>
<% if f.object.user_basic_post_quota? %>
<div class="form-group">
<div class="col-6">
<%= f.error_notification %>
</div>
</div>
<% else %>
<div class="form-group">
<div class="col-5">
<label for="post-title">Post Title</label>
<%= f.input :post_title, class: 'form-control', label: false, required: true, placeholder: '' %>
</div>
</div>
<% end %>
<% end %>
posts_controller.rb
# GET /posts/new
def new
@post = Post.new
end
新方法
post.rb
def user_basic_post_quota?
if current_user.subscription_plan.id == 2 && current_user.posts.where(:created_at => (Time.zone.now.beginning_of_month..Time.zone.now)).count >= 800
errors.add(:base, "Exceeded The Amount of Post That You Can Create For Your Account!")
end
end
错误
ActionView::Template::Error (undefined method `subscription_plan' for nil:NilClass):
1: <div class="container">
2: <%= simple_form_for(@post) do |f| %>
3: <% if f.object.user_basic_post_quota? %>
4: <div class="form-group">
5: <div class="col-6">
6: <%= f.error_notification %>
如果您有更好的方法,请通知我。
答案 0 :(得分:0)
在您的模型中,您无法使用current_user
。您可以将它传递给方法。然后你的方法看起来像
def user_basic_post_quota?(user)
if user.subscription_plan.id == 2 && user.posts.where(:created_at => (Time.zone.now.beginning_of_month..Time.zone.now)).count >= 800
errors.add(:base, "Exceeded The Amount of Post That You Can Create For Your Account!")
end
end
你可以从你的控制器(current_user
存在的地方)调用它,比如
Post.user_basic_post_quota?(current_user)
然后你的行动将是
def new
@post = Post.new
@quota_exceeded = Post.user_basic_post_quota?(current_user)
end
和您的观点
<%= simple_form_for(@post) do |f| %>
<% if @quota_exceeded %>
<div class="form-group">
<div class="col-6">
<%= f.error_notification %>
</div>
</div>
<% else %>
<div class="form-group">
<div class="col-5">
<label for="post-title">Post Title</label>
<%= f.input :post_title, class: 'form-control', label: false, required: true, placeholder: '' %>
</div>
</div>
<% end %>
<% end %>
但我相信您的user_basic_post_quota?
方法是专为自定义验证而设计的,因为它会根据条件将错误添加到Post
对象中。但在这种情况下,除了Post
对象验证之外,它实际上不应该被调用。
然而,如果你想检查配额是否超出你的方法可能看起来像
def user_basic_post_quota?(user)
user.subscription_plan.id == 2 && user.posts.where(:created_at => (Time.zone.now.beginning_of_month..Time.zone.now)).count >= 800
end
如果超出配额,它将只返回true
,否则返回false
。