Skip to content

ActiveStorage with Rails API #32500

@NicholasLYang

Description

@NicholasLYang

I'm basically trying to get ActiveStorage working with Rails API. The main issue I have is getting a URL from an Attachment object. url_for doesn't work outside of Rails views, so I cannot get the url from that. In addition, I'm not quite clear on creating an article with an image. The following code when run in the Rails console does not create an attachment:

School.create(name: "New York University", image: File.open(Rails.root + "db/sample.jpg"))

Instead, it simply gives the following:

(0.1ms)  begin transaction
  School Create (0.8ms)  INSERT INTO "schools" ("name", "created_at", "updated_at") VALUES (?, ?, ?)  [["name", "New York University"], ["created_at", "2018-04-09 03:36:54.304927"], ["updated_at", "2018-04-09 03:36:54.304927"]]
   (2.8ms)  commit transaction
=> #<School id: 4, name: "New York University", created_at: "2018-04-09 03:36:54", updated_at: "2018-04-09 03:36:54">

Steps to reproduce

Try to run url_for in the Rails console.

Expected behavior

I get the url. Granted, I get that this is not the purpose of url_for (it's a view helper, not a method). But I'd like some equivalent, ideally a method in the ActiveStorage::Attached object.

Actual behavior

url_for gives the following error: (undefined method 'url_for' for main:Object). Even when I include the Rails view helpers, I get the following:

ArgumentError (Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true)

I could try adding a host to the ActiveStorage::Attached object, but that's sorta hackneyed as splats don't work with it, and I can't mutate it easily.

System configuration

Rails version:
5.2.0.rc2
Ruby version:
ruby 2.5.0p0

Thank you for your time. I understand that ActiveStorage is not fully stable or released yet, but it looked too damn cool to not use 😄 . I'd be open to contributing/opening a PR if someone could point me in the right direction.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions