Search code examples
javascriptjqueryruby-on-railsruby-on-rails-3models

Submit value to Rails Model


if i have this as my form

<%= form_for @rating, :id =>"ratingForm" do |f| %>
<%= f.hidden_field :ratings, :value => '' %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<%= f.hidden_field :recipe_id, :value => @recipe.id %>
<div class="rateit" id="rateit10">
</div>
<%= f.submit "Submit" %>
<% end %>

How do i pass the value of the content within this div

<div class="rateit" id="rateit10">
</div>

if i use this jquery I can get the value of rateit10

$("#rateit10").bind('rated', function() { 
 $(this).rateit('value');
  });

The value derives from clicking upon a set of stars, im trying to implement a rating system in rails using the Rateit plugin


Solution

  • This will pass a hash to your controller method:

       function pass_to_controller(){
        var rate_value = $("#ratings").value();
        var user_id = $("#user_id").value();  /*you already have access to this through current_user.id */
        var recipe_id = $("#recipe_id").value();
    
        $.ajax({
            type: "Get",
            url: "path_to_your_controller_action_here",
            timeout: 5000,
            data: {rating : rate_value, user : user_id, recipe : recipe_id }
        }).done(function(response){//do your response here});
    }
    

    You can't directly pass to the model - that circumvents the whole thought process behind MVC. So the best way to do it is to use ajax, pass it to your controller method, then if you need to do something in your database call your model method.

    The advantage of using ajax like this is that it won't reload your page when someone rates something.