我创建了一个应用程序,用户可以每天邀请某人参加一小时的培训。我希望当用户已经邀请了某人时,该按钮在其他培训课程中消失,当它进入培训节目时,他邀请用户按钮"取消邀请"出现。我已经有了创建和删除的方法。我需要有关此代码逻辑的帮助。
这些是我的模型(用户,访客和培训):
training.rb
class Training < ApplicationRecord
has_many :users, through: :bookings
has_many :bookings
has_many :guests
end
user.rb
class User < ApplicationRecord
has_many :trainings, through: :bookings
has_many :bookings, dependent: :destroy
has_many :guests, dependent: :destroy
accepts_nested_attributes_for :guests
end
guest.rb
class Guest < ApplicationRecord
belongs_to :training
belongs_to :user
validates :user_id, presence: true
validates :training_id, presence: true
validate :training_not_full?, on: :create
end
config routes.rb:
Rails.application.routes.draw do
root 'static_pages#home'
get '/signup', to: 'users#new'
get '/contact', to: 'static_pages#contact'
get '/about', to: 'static_pages#about'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :users do
resources :rms
end
resources :trainings do
resources :guests
resources :bookings
end
end
这是我尝试过的逻辑(不工作):
<% if current_user.trainings.any? %>
<%= link_to "Cancel invitation",
training_guest_path(@training, @training.guests.where(user: current_user).first),
method: :delete,
data: { confirm: "Sure??" },
class: "btn btn-primary" %>
<% else %>
<%= link_to "Invite", new_training_guest_path(current_user), class: "btn btn-primary" %>
<% end %>
答案 0 :(得分:1)
创建Invitation
模型,如下所示:
class CreateInvitations < ActiveRecord::Migration[5.0]
def change
create_table :invitations do |t|
t.string :user_id
t.string :guest_id
t.timestamps
end
end
end
class Invitation < ApplicationRecord
belongs_to :user
has_many :guests
end
然后检查用户是否在过去24小时内邀请了某位访客:
last_invitation_date = user.invitations.order(:created_at).last.created_at
can_invite = last_invitation_date < DateTime.now - 1.day