Edi Junior
Edi Junior

Reputation: 49

How can I save a field as other field in other table?

I have an authentication feature that provides me the username of the current user. I also have a table of events (created by users). And when a user creates an event, how could I save a field called host with the current name of this user in the table events?

Upvotes: 0

Views: 30

Answers (2)

Jay-Ar Polidario
Jay-Ar Polidario

Reputation: 6603

Or, if your Event doesn't belongs_to :user, then you'll need to update this manually in the controller as follows

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

Upvotes: 1

Jay-Ar Polidario
Jay-Ar Polidario

Reputation: 6603

The concept is called "deserialization", which is why I made my own gem for this: quickery.

Using quickery

class Event < ApplicationRecord
  belongs_to: user

  quickery { user: { username: :host } }
end

Using Normal-Way

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

Usage Example (for either above)

user = User.create!(username: 'foobar')
event = Event.create!(user: user)
puts event.host
# => 'foobar'

Upvotes: 1

Related Questions