我正在尝试让订阅者通过删除表单取消订阅,然后他们输入电子邮件,然后提交然后删除订阅。不知道为什么这不起作用。我通过我的控制器尝试了很多东西。会喜欢一些建议或替代方案。
目前收到此错误
Couldn't find Subscription without an ID
订阅控制器
def destroy
@subscriptions = Subscription.all
@subscription = @subscriptions.find(params[:id])
if @subscription.email == params[:email]
@subscription.destroy
flash[:notice] = "You have been unsubscribed"
redirect_to root_path
else
end
end
路线
Rails.application.routes.draw do
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
get 'users/new'
resources :posts
root 'static_pages#new_home'
resources :subscriptions, only: [:new, :create, :edit, :update, :show, :destroy]
get '/home' => 'static_pages#home'
get 'subscriptions' => 'subscriptions#show'
delete 'subscriptions' => 'subscriptions#destroy'
get '/about' => 'static_pages#about'
get '/author' => 'static_pages#author'
get '/contact' => 'static_pages#contact'
get '/book' => 'static_pages#book'
get '/signup' => 'users#new'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :posts do
resources :comments
end
end
取消订阅订阅视图中的部分
<%= form_for @subscription, method: :delete do |f| %>
<div class="row">
<h2>Unsubscribe</h2>
</div>
<div class="row newsletter">
<form method="post" action="#" class="contact-form">
<div class="row email-label">
<%= f.label :email, :class => 'label-email' %>
<%= f.email_field :email %>
</div>
<div class="row">
<%= f.submit 'Unsubscribe', :class => 'btn-full-subscribe' %>
</div>
</form>
</center
<% end %>
我尝试了许多没有运气的事情。帮助将不胜感激。谢谢。订阅与用户模型无关。
答案 0 :(得分:1)
此行@subscription = @subscriptions.find(params[:email])
导致此问题。
尝试@subscription = @subscriptions.find_by_email(params[:email])
或更好,请使用ID @subscription = @subscriptions.find(params[:id])
。
ActiveRecord::find
仅使用ID:http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find。
答案 1 :(得分:0)
问题在这里
@subscription = @subscriptions.find(params[:email])
因为如果您想要通过任何其他字段提取,则使用ID来获取记录find_by_"attribute_name"
,将其替换为
@subscription = Subscription.find_by_email(params[:email])
或者无需写下额外的代码。无需获取所有订阅。删除使用
@subscription = Subscription.find_by_email(params[:email])
or
@subscription = Subscription.find(params[:id])
if @subscription.destroy
flash[:notice] = "You have been unsubscribed"
redirect_to root_path
end