Rails 4 has_many通过连接表管理属性增加

时间:2014-03-22 14:53:34

标签: ruby-on-rails ruby-on-rails-4

我在Rails 4中使用简单的has_many:通过关联:

class Plan < ActiveRecord::Base
  belongs_to :project
  belongs_to :item
  quantity: decimal
end

class Project < ActiveRecord::Base
  has_many :plans
  has_many :items, through: :plans
end

class Item < ActiveRecord::Base
  has_many :plans
  has_many :projects, through: :plans
  belongs_to :unit
end

我有6个计划:

2.1.1 :002 > Plan.all.count
   (0.1ms)  SELECT COUNT(*) FROM "plans"
=> 6

我无法访问数量属性:

2.1.1 :014 > Plan.where(item_id: 1, project_id: 2).count
   (0.1ms)  SELECT COUNT(*) FROM "plans" WHERE "plans"."item_id" = 1 AND "plans"."project_id" = 2
 => 1 
2.1.1 :015 > Plan.where(item_id: 1, project_id: 2).quantity
NoMethodError:   Plan Load (0.1ms)  SELECT "plans".* FROM "plans" WHERE "plans"."item_id" = 1 AND "plans"."project_id" = 2
undefined method `quantity' for #<ActiveRecord::Relation::ActiveRecord_Relation_Plan:0x000000020a8d48>

当计划包含一个项目并再添加一个项目时,则必须增加数量。

计划管制员:

def create
   @plan = Plan.new(plan_params)
   @plan.project_id =  @project.id
    if @project.plans.where(:item_id => @plan.item_id).blank?
      @plan.save
      redirect_to project_plans_url
    else
      **?????**
      redirect_to project_plans_url
    end
  end

private
  def set_project
    @project = Project.find(params[:project_id])
  end

  def plan_params
    params.require(:plan).permit(:item_id, :quantity)
  end

如何管理控制器其他分支?

1 个答案:

答案 0 :(得分:0)

你需要这样的东西:

@plan.project_id =  @project.id
new_plan = @project.plans.where(item_id: @plan.item_id).first_or_initialize
new_plan.quantity += 1
new_plan.save

在这种情况下你根本不需要别人。