自动将一堆对象分配给Rails中的另一个对象

时间:2017-05-17 20:23:58

标签: ruby-on-rails ruby-on-rails-5

可怕的称号,但不知道怎么说这句话。

情况如下:

我有一个应用程序,用户可以注册并为孩子们做活动。因此,有一个用户模型,子模型和活动模型。

用户有很多孩子,孩子通过ChildActivity模型与活动有关系。用户可以标记他们的孩子已完成的活动。

当用户创建孩子时,我希望自动将10个孩子年龄范围内的活动分配给该孩子。活动有最小年龄和最大年龄,儿童有固定年龄。

我不知道的是在创建子项时自动为子项分配活动的最佳方法。

您对此有任何指导意见,我们将不胜感激。包括我的代码以供参考。

模型/ child.rb

class Child < ApplicationRecord

belongs_to :user

has_many :child_activities
has_many :activities, through: :child_activities, class_name: 'Activity'

end

user.rb

class User < ApplicationRecord
 devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
 has_many :children, dependent: :destroy
 accepts_nested_attributes_for :children, allow_destroy: true
end

控制器/ children_controller.rb

class ChildrenController < ApplicationController

 def new
    @user = current_user.find(params[:user_id])
    @child = Child.new
 end

 def create
    @child = current_user.children.build(child_params)
  if @child.save
    redirect_back(fallback_location: root_path, notice: "You have added a child!")
  else
    redirect_back(fallback_location: root_path, notice: "Something went wrong — please try again.")
  end 
end

def update
    if @child.update(child_params)
    redirect_back(fallback_location: root_path)
  else
    redirect_back(fallback_location: root_path)
  end 
end

private

    def child_params
        params.require(:child).permit(:name, :age, :user_id, :created_at, :updated_at)
    end

end

控制器/ registrations_controller.rb

class Users::RegistrationsController < Devise::RegistrationsController

def new
  @user = User.new
  @user.children.build
end

private

def after_sign_up_path_for(resource)
 root_path
end
end

1 个答案:

答案 0 :(得分:0)

比我想象的更容易。刚刚为我的Child模型添加了一个方法。代码如下。

class Child < ApplicationRecord
acts_as_voter
belongs_to :user
after_save :add_activities

has_many :child_activities
has_many :activities, through: :child_activities, class_name: 'Activity'

has_many :completions
has_many :completed_activities, :through => :completions, :source => :completable, :source_type => "Activity"

private

def add_activities
    @activities = Activity.where('min_age <= ? AND max_age >= ?', self.age, self.age) 
    @activities.each do |activity|
        self.child_activities.create(:activity_id => activity.id)
    end
end

end