Simply scenario — I have two buttons both of which call the same controller/action. The controller action sets a random number, @random_number.
If I click button 1, I want the view to change (via JS) by displaying the @random_number in RED. If I click button 2, I want the view to change (via JS) by displaying the @random_number in GREEN.
What is the DRY-est way to do this? My understanding of rails’s controller/view layers is that each controller/action is associated with a corresponding view. But in this case, I want to use the same business logic (generate a random number) for both button clicks but the resulting view depends on which button is clicked.
One option is to pass the button id to the controller/action and then use the button id in the controller/action’s associated RJS file to execute the appropriate javascript. But my gut tells me that this is not the best way. Is there a better way?
A quick code sample would be much appreciated.
Thanks.
You should have the same view and same controller method generate a random number. However, at the front end you should use javascript or jquery to set the color property of the test. To start with such an approach you could look into ajaxSuccess and click event binders in jquery.
Another approach, if you want to avoid using javascript, would be to set a data value in your link field(HTML5). The data value should be sent to the controller as part of the request that is generated. This should simply be set when you’re displaying the text dynamically. This way you won’t be repeating any part of the code in the view or controller.