[英]Setting up Rails Controller for the through in has_many through relationship
我正在創建一個具有多對多模型的Rails Web應用程序。 該應用程序允許用戶使用許多預定義的“小部件”填充其儀表板。 因此,我有一個用戶表(由devise創建和管理)和一個小部件表。 都好。 因此,要管理直通位,我有一個“下標”表。 這是我的模型:
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
但是,我不太了解如何創建訂閱。 理想情況下,我希望創建表單僅具有一個選擇器以從所有可用的小部件中進行選擇,然后使用當前user:id
但是我不確定這將如何工作,這是我的控制器:
def new
@subscription = Subscription.new
end
def create
@user = current_user
@subscription = @user.subscriptions.build(subscription_params)
respond_to do |format|
if @subscription.save
format.html { redirect_to @subscription, notice: 'subscription was successfully created.' }
format.json { render :show, status: :created, location: @subscription }
else
format.html { render :new }
format.json { render json: @subscription.errors, status: :unprocessable_entity }
end
end
end
我非常希望能朝正確的方向前進,因為我無法從官方文檔中了解如何完成此操作,也沒有找到與此相關的任何優秀教程。
假設您在訂閱上沒有任何其他屬性,則可以使用has_many
在用戶上創建的widget_ids=
方法
控制者
class UserSubscriptionsController
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
視圖
<%= form_for @user, url: user_subscription_path, method: :patch do |f| %>
<%= f.collection_check_boxes :widget_ids, Widget.all, :id, :name %>
<%= f.submit %>
<% end %>
在我的示例中,路線
resource :user_subscription, only: [:edit, :update]
但是顯然,您可以根據自己的路線進行修改。 更新用戶時,Rails會自動創建訂閱。
相反,您可以根據需要在正常編輯用戶時僅使用collection_check_boxes
。 還有collection_select
您可以使用訂閱表單保存此類數據。
= form_for @subscription do |f|
= f.select :widget_id, options_from_collection_for_select(Widget.all, "id", "title"), {}, {:class => "form-control select" }
= f.hidden_field :user_id, :value => current_user.id
#other subscription fields
= f.submit
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.