3

I am a beginner at rails development and moved from cakephp.

In cakephp there's something you can do in the layout to automatically include any javascript files that are named the same as either the controller or the action.

For instance in www.website.com/post/add

both post.js and post/add.js will automatically be loaded if they exist.

Is there a way to do this in rails? I tried doing a google but didn't know what to search for and didn't turn up much.

(Same thing with css)

1 Answer 1

7

I'm not aware of this kind of functionality in rails, but you can simply do this in a layout:

javascript_include_tag "#{controller.controller_name}"
javascript_include_tag "#{controller.action_name}"

it will not check if the file exists, so you can go further and create application helper, and move there a logic of js including and checking if file exists:

def include_controller_js
 javascript_include_tag "#{controller.controller_name}" if File.exists?("#{Rails.root}/public/javascripts/#{controller_name}.js")
end

But since rails 3.1 there is an asset pipeline with application.js manifest file, so maybe you would like to read more about it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.