开发者

Rails -- is IRB necessary?

开发者 https://www.devze.com 2023-03-14 01:46 出处:网络
I am following Michael Hartl\'s RoR toturial and there are multiple places where he uses IRB, often to add users to the database.When I use rails console to open IRB and then create a User in the data

I am following Michael Hartl's RoR toturial and there are multiple places where he uses IRB, often to add users to the database. When I use rails console to open IRB and then create a User in the databa开发者_Go百科se everything works fine, but if I try to do the same thing by running the same line of code from a file like test.rb in the directory of my application it doesn't work b/c it says it can't find the User model. Is there any way I can run these lines of code (i.e. for putting a user into a database) from a .rb file rather than from the IRB?


For a separate script look into rails runner. It loads the Rails backend so you have access to all the models and exists for this purpose.

From the "Ruby on Rails Guides":

runner runs Ruby code in the context of Rails non-interactively. For instance:

$ rails runner "Model.long_running_method"


If you're just using test.rb as a convenience to save and re-run console commands, you could do this:

rails console < test.rb

Or, as a bit of a hack, put this at the top of your test.rb:

require 'config/environment'

And invoke it from the app's root directory like this:

ruby -I . test.rb


Placing a ruby file in the folder of your app doesn't automatically load up your Rails app. You need to explicitly load the config/environment.rb file to load the Rails app.

If your test.rb is in the root of your app, you can do something like

require File.expand_path("../config/environment", __FILE__)
# Access your models here
0

精彩评论

暂无评论...
验证码 换一张
取 消