Ruby on Rails: Using user input for calculations on the same page

拜拜、爱过 提交于 2019-12-13 01:28:12

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/21272875/ruby-on-rails-using-user-input-for-calculations-on-the-same-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!