Creating a created_by column and association with rails?
activerecord, associations, model, ruby, ruby-on-rails
Solution
The other way to associate the view (Rails 4 & 5)
belongs_to :created_by, class_name: "User", foreign_key: "created_by_id"
if two or more associations to one Class (i.e. "User") are needed.
Example: I'd like to create User(:email, :password) and associate it with profile(:name, :surname). But I'd also like to add User an ability to create profile of other users with their :emails (and further send invitations to them).
create Profile (belongs_to User) and User (has_one Profile). This association creates user_id column in Profiles table.
In generated Profiles table migration file add this lines:
t.belongs_to :user, index: true, optional: true
So the association becomes:
"Users 1 - 1..0 Profiles", kind of relation(so the profile might and might not have user_id)
Add the association mentioned at the top to Profile model.
belongs_to :created_by, class_name: "User", foreign_key: "created_by_id"
Add `@user.created_by = current_user` in Profile#create action
Problem
Sigh... I feel like a big newbie on this one, so lets say I have a few models: ``` class Question < ActiveRecord::Base has_many :answers belongs_to :user end class Answer < ActiveRecord::Base belongs_to :question has_one :user end class User < ActiveRecord::Base has_many :questions has_many :answers, :through => :questions end ``` so my issue is that I don't know how to get the user that created the question or answer, the user should be determined when the question (or answer is created) is created, and the user should come from the current user's sessions (from authlogic's user model and controller) see here: ``` class ApplicationController < ActionController::Base helper_method :current_user_session, :current_user ... private def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.user end end ``` Now, the current_user helper method works fine, but how can I set what user created the question or answer? like id like to just say @question.user btw, my schema for my question has a created_by column, but when I create a new question it stays null.