如何将一个字段另存为其他表中的其他字段?

时间:2019-06-11 17:45:09

标签: ruby-on-rails

我具有身份验证功能,可以向我提供当前用户的用户名。我还有一张事件表(由用户创建)。当用户创建事件时,如何在表事件中使用该用户的当前名称保存名为host的字段?

2 个答案:

答案 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