Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using asset_path in Rails console

In my Character model I have added:

character.rb

before_save do
  self.profile_picture_url = asset_path('icon.png')
end

However, for all the Characters that already exist in the database, their profile_picture_url is nil. I therefore want to enter the console and iterate through all of them and set it. In the console I tried:

Character.find_each do |c|
  c.profile_picture_url = asset_path('icon.png')
end

But this gives the error:

NoMethodError: undefined method `asset_path' for main:Object

I hope I have adequately communicated what I am trying to achieve. Where am I going wrong?

like image 430
Bazley Avatar asked Jul 21 '17 00:07

Bazley


2 Answers

Check out the documentation for AssetHelper:

This module provides methods for generating asset paths and urls.

You can access asset_path in the console a few ways:

ActionController::Base.helpers.asset_path('icon.png')

Or

include ActionView::Helpers::AssetUrlHelper
asset_path('icon.png')

Also on a side note and separate from the question, if you are updating all of your Character's I would use update_all for your profile_picture_url attribute.

Character.update_all(profile_picture_url: asset_path('icon.png')
like image 50
jdgray Avatar answered Sep 30 '22 17:09

jdgray


If you are trying to call asset_path, other than helpers or views, then call like

ActionController::Base.helpers.asset_path("icon.png")
like image 40
Neeraj Kumar Avatar answered Sep 30 '22 16:09

Neeraj Kumar