2017-05-17 12 views
0

ひどいタイトルですが、それ以外の言い方は分かりませんでした。複数のオブジェクトをRailsの別のオブジェクトに自動的に割り当てる

私は、ユーザーがサインアップして行うために彼らの子供のための活動を得ることができるアプリを持っている:

状況がこれです。したがって、Userモデル、Childモデル、およびActivityモデルがあります。

ユーザーには多くの子があり、子アクティビティには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 

答えて

0

は、私が思ったより簡単になってしまいました。ちょうど私の子モデルにメソッドを追加しました。以下のコード。

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 
関連する問題