Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ branch = ENV.fetch("BRANCH", "main")
gem "activesupport", github: "rails/rails", branch: branch
gem "activemodel", github: "rails/rails", branch: branch
gem "activejob", github: "rails/rails", branch: branch
gem "activerecord", github: "rails/rails", branch: branch
gem "sqlite3"

gem "rubocop"
gem "rubocop-minitest"
Expand Down
12 changes: 12 additions & 0 deletions lib/active_resource/associations/active_record.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

module ActiveResource
module Associations
module ActiveRecord
def belongs_to_resource(name, class_name: nil)
klass = class_name&.constantize || name.to_s.classify.constantize
define_method(name) { klass.find(send("#{name}_id")) }
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this issue an HTTP request each time the method is invoked?

end
end
end
end
6 changes: 6 additions & 0 deletions lib/active_resource/railtie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,11 @@ class Railtie < Rails::Railtie
app.config.active_job.custom_serializers << ActiveResource::ActiveJobSerializer
end
end

initializer "active_resource.patch_active_record" do |app|
ActiveSupport.on_load(:active_record) do
ActiveRecord::Base.extend(ActiveResource::Associations::ActiveRecord)
end
end
end
end
42 changes: 42 additions & 0 deletions test/cases/active_record_association_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# frozen_string_literal: true

require "active_record"
require "active_resource/associations/active_record"

class ActiveRecordAssociationTest < ActiveSupport::TestCase
setup do
setup_response # find me in abstract_unit

ActiveRecord::Base.establish_connection(
adapter: "sqlite3",
database: ":memory:"
)
ActiveRecord::Schema.define do
self.verbose = false

create_table :test_records, force: true do |t|
t.string :name
t.belongs_to :person
t.belongs_to :book
t.timestamps
end
end

ActiveRecord::Base.extend(ActiveResource::Associations::ActiveRecord)

class TestRecord < ActiveRecord::Base
belongs_to_resource :person
belongs_to_resource :book, class_name: "Product"
end
end

def test_belongs_to_resource
record = TestRecord.create(name: "test", person_id: 1)
assert_equal record.person.name, "Matz"
end

def test_belongs_to_resource_with_class_name
record = TestRecord.create(name: "test", person_id: 1, book_id: 1)
assert_equal record.book.name, "Rails book"
end
end