Reputation: 541
So, I'm having issues with what I think is a really simple problem. I don't know how to access user input...or perhaps I don't know how to declare a temporary variable in rails.
Anyway, what is the most straight forward way of accomplishing this:
<div>
Enter Group Size: <%= number_field_tag(:group_size)%>
Select Study Site: <%= number_field_tag(:site) %>
</div>
<% if :site > 4 %>
Hello!
<% else %>
Nope!
<% end %>
I suppose I'll need javascript to actually make it work, but for now I just need to know how to use these variables.
Any help would be greatly appreciated. Thanks.
Upvotes: 1
Views: 792
Reputation: 76784
As with most things, the solution is a lot more involved:
Ajax
Unlike native apps, Rails relies on the HTTP protocol
HTTP works on requests. You send requests to a server to render a web page; the server responds to the requests. The problem with this is you cannot use Rails with "live" functionality without sending requests to-and-from the server (even "live" applications just keep a perpetual connection open, acting as a single request)
This means if you want to process "live" data (without refresh), you'll have to use a technology to send a request on your behalf. As you noted, this will be ajax:
$(".element").on("action", function(){
$.ajax({
url: "your/end/point"
data: {your: data}
success: function(data) {
alert(data)
}
});
});
Rails
To handle an ajax request in Rails, it's basically the same as handling an HTTP request:
#config/routes.rb
resources :controller do
get :your_endpoint
end
#app/controllers/controllers_controller.rb
def your_endpoint
# perform actions here
respond_to do |format|
format.html
format.js { # handles JS / Ajax request }
end
end
Return
You can then handle the returned data with your JS (Ajax) function. This gives the image that it's working in "real time", but will actually be sending & receiving requests from the server every time
Upvotes: 2
Reputation: 3026
To use them dynamically with ERB, they need to be wrapped in a form and submitted to the server. You can then access them easily with params[:variable_name]
. It would probably be cleaner to prepare the message in the controller, but if you don't need to interact with models, it would be more straightforward to use some basic JS to do everything.
Upvotes: 4