Skip to content

Build the has_one child path from the parent's prefix - #479

Open
RaphaelFakhri wants to merge 1 commit into
rails:mainfrom
RaphaelFakhri:fix-has-one-site-path
Open

RaphaelFakhri wants to merge 1 commit into
rails:mainfrom
RaphaelFakhri:fix-has-one-site-path

Conversation

@RaphaelFakhri

Copy link
Copy Markdown

Summary

When the associated class is not a singleton, has_one fetches the record from "/#{collection_name}/#{id}/#{name}.json". The connection merges that absolute path into site, so the path of the parent's site is lost, and the parent's prefix options are never applied.

class Post < ActiveResource::Base
  self.site = "http://example.com/api/v1"
  has_one :author, class_name: "Person"
end

Post.find(1).author # GET /posts/1/author.json, expected /api/v1/posts/1/author.json

class Comment < ActiveResource::Base
  self.site = "http://example.com/posts/:post_id"
  has_one :author, class_name: "Person"
end

Comment.find(1, params: { post_id: 5 }).author # GET /comments/1/author.json, expected /posts/5/comments/1/author.json

This change builds the path from self.class.prefix(prefix_options), the same way element_path and custom methods build theirs, and encodes the id with ERB::Util.url_encode to match element_path.

Fixes #334. Earlier attempts (#300, #333) were closed as stale without review.

Tests

Two tests in test/cases/base_test.rb cover a parent site with a path and a parent with a prefix parameter. Both fail on main with ActiveResource::InvalidRequestError for the wrong URL and pass with this change. bundle exec rake test and rubocop pass.

When the associated class is not a singleton, `has_one` fetched the
record from `"/#{collection_name}/#{id}/#{name}.json"`. The leading `/`
replaces the path of the parent's `site` when the connection merges it,
and the parent's prefix options are never applied. For a parent with
`self.site = "http://example.com/api/v1"`, `post.author` requested
`/posts/1/author.json` instead of `/api/v1/posts/1/author.json`, and a
nested parent such as `/posts/:post_id/comments` requested
`/comments/1/author.json`.

Build the path from `prefix(prefix_options)`, like `element_path` and
custom methods do, and encode the id as a path segment.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Site paths are stripped of path when using has_one associations

1 participant