Skip to content

Instantly share code, notes, and snippets.

@elct9620
Created April 2, 2014 13:18
Show Gist options
  • Save elct9620/9933903 to your computer and use it in GitHub Desktop.
Save elct9620/9933903 to your computer and use it in GitHub Desktop.
has many through with join table attributes when create or query
user = User.create()
user.logs << Log.new
user.send_logs << Log.new # join table "action" column will assign "send" as default
user.receive_logs << Log.new # join table "action" column will assign "receive" as default
class LogRelationships < ActiveRecord::Base
belongs_to :log
belongs_to :user
end
class User < ActiveRecord::Base
# Select ALL
has_many :log_relationships
has_many :logs, through: :log_relationships
# Select Type "send"
has_many :send_log_relationships, class_name: "LogRelationships", conditions: { action: "send" }
has_many :send_logs, through: :send_log_relationships, source: :log
# Select Type "receive"
has_many :receive_log_relationships, class_name: "LogRelationships", conditions: { action: "receive" }
has_many :receive_logs, through: :receive_log_relationships, source: :log
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment