我具有身份验证功能,可以向我提供当前用户的用户名。我还有一张事件表(由用户创建)。当用户创建事件时,如何在表事件中使用该用户的当前名称保存名为host的字段?
答案 0 :(得分:1)
这个概念称为“反序列化”,这就是为什么我为此制作了自己的瑰宝:quickery
。
quickery
class Event < ApplicationRecord
belongs_to: user
quickery { user: { username: :host } }
end
class Event < ApplicationRecord
belongs_to :user
before_save do
host = user.username
end
end
class User < ApplicationRecord
has_many :events
# you may want to comment out this `after_destroy`, if you don't want to cascade when deleted
after_destroy do
events.update_all(host: nil)
end
# you may want to comment out this `after_update`, if you don't want each `event.host` to be updated (automatically) whenever this `user.username` gets updated
after_update do
events.update_all(host: username)
end
end
user = User.create!(username: 'foobar')
event = Event.create!(user: user)
puts event.host
# => 'foobar'
答案 1 :(得分:1)
或者,如果您的Event
不是belongs_to :user
,则需要按照以下说明在控制器中手动更新
class EventsController < ApplicationController
def create
@event = Event.new
@event.assign_attributes(event_params)
@event.host = current_user.username
if @event.save
# success, do something UPDATE THIS
else
# validation errors, do something UPDATE THIS
end
end
def update
@event = Event.find(params[:id])
@event.assign_attributes(event_params)
@event.host = current_user.username
if @event.save
# success, do something UPDATE THIS
else
# validation errors, do something UPDATE THIS
end
end
private
def event_params
params.require(:event).permit(:someattribute1, :someattribute2) # etc. UPDATE THIS
end
end