【发布时间】:2015-07-06 16:11:13
【问题描述】:
我有一个市场,我的用户可以在其中创建计划,他们的客户可以加入他们。所以我有一个计划模型和一个客户模型。最终目标是为客户订阅计划,因此我创建了一个订阅模型和一个 has_many :through 关联,但我需要一些帮助才能使创建正常工作。在订阅能够发生时,计划和客户已经存在,因此我无需担心在订阅#create 上创建计划或客户,我只需要担心加入现有的计划或客户。
我现在所处的位置是创建订阅模型,但它没有关联到正确的客户。我需要为我订阅该计划的每个客户创建一个订阅模型,并且我正在使用多选标签。
我使用 has_many :through 因为一个计划有很多客户,但一个客户也可以有很多计划。
如果有什么不清楚的地方请告诉我,我试图尽可能清晰简洁地解释它。
计划模型
class Plan < ActiveRecord::Base
has_many :subscriptions
has_many :customers, through: :subscriptions
end
客户模型
class Customer < ActiveRecord::Base
has_many :subscriptions
has_many :plans, through: :subscriptions, dependent: :delete_all
end
订阅模式
class Subscription < ActiveRecord::Base
belongs_to :plan
belongs_to :customer
end
Routes.rb
resources :customers
resources :plans do
resources :subscriptions
end
订阅控制器
class SubscriptionsController < ApplicationController
def new
@user = current_user
@company = @user.company
@plan = Plan.find(params[:plan_id])
@subscription = Subscription.new
end
def create
if @subscription = Subscription.create(plan_id: params[:subscription][:plan_id] )
@subscription.customer_id = params[:subscription][:customer_id]
@subscription.save
flash[:success] = "Successfully Added Customers to Plan"
redirect_to plan_path(params[:subscription][:plan_id])
else
flash[:danger] = "There was a problem adding your customers to this plan"
render :new
end
end
private
def subscription_params
params.require(:subscription).permit(:customer_id, :plan_id, :stripe_subscription_id)
end
end
表格:
<%= form_for [@plan, @subscription] do |f| %>
<%= f.hidden_field :plan_id, value: @plan.id %>
<div class="row">
<div class="col-md-6">
<%= f.select :customer_id, options_from_collection_for_select(@company.customers, 'id', 'customer_name', @plan.customers), {}, multiple: true, style: "width: 50%;" %><br />
</div>
<div class="col-md-12">
<%= f.submit "Add Customer To Plan", class: "btn btn-success pull-right" %>
</div>
</div>
<% end %>
参数:
{"utf8"=>"✓",
"authenticity_token"=>"###",
"subscription"=>{"plan_id"=>"5", "customer_id"=>["", "153", "155"]},
"commit"=>"Add Customer To Plan",
"action"=>"create",
"controller"=>"subscriptions",
"plan_id"=>"5"}
【问题讨论】:
-
你可以用
@subscription = Subscription.create(params[:subscription])替换这个@subscription = Subscription.create(plan_id: params[:subscription][:plan_id] ) -
@MaxWilliams 当我尝试这样做时,我得到了一个严重的参数错误,说禁止属性。当我做
Subscription.create(subscription_params)时,我遇到了与客户无关的同样问题。
标签: ruby-on-rails ruby-on-rails-4 activerecord has-many-through nested-resources