我有以下rails应用程序,它允许用户订阅小部件。即通过订阅的用户到小部件的多对多模型。
我的模特:
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :widget
validates_uniqueness_of :user_id, scope: :widget_id
end
class User < ActiveRecord::Base
has_many :subscriptions
has_many :widgets, through: :subscriptions
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
class Widget < ActiveRecord::Base
has_many :subscriptions
has_many :users, through: :subscriptions
end
我的控制器:
class SubscriptionsController
def edit
@user = current_user
end
def update
@user = current_user
if @user.update(user_subscription_params)
redirect_to @user, notice: "Subscriptions updated"
else
render :edit
end
end
private
def user_subscription_params
params.require(:user).permit(:widget_ids)
end
end
这是在views/subscriptions/_forms.html.erb
中呈现的,如下所示:
<%= form_for @user, url: user_subscription_path, method: :patch do |f| %>
<%= f.collection_check_boxes :widget_ids, Widget.all, :id, :name %>
<%= f.submit %>
<% end %>
我收到错误:
没有路由匹配{:action =&gt;&#34; show&#34;,:controller =&gt;&#34; subscriptions&#34;}缺少必需的密钥:[:id]
我真的很感激如何解决这个问题。
编辑:
routes.rb中:
Rails.application.routes.draw do
root 'home#index'
resources :widgets
resources :subscriptions
devise_for :users
devise_scope :user do
get '/users/sign_out' => 'devise/sessions#destroy'
end
authenticated :user do
root to: 'home#index', as: :authenticated_root
end
答案 0 :(得分:0)
你可以尝试
<%= form_for @user, url: user_subscription_path(@user), method: :patch do |f| %>
<%= f.collection_check_boxes :widget_ids, Widget.all, :id, :name %>
<%= f.submit %>
<% end %>