Richlewis
Richlewis

Reputation: 15374

Pass value via hidden_field in rails

I am trying to implement a rating system in my app, i tried Rateit but couldnt get it to work so thought I would try and build my own, plus this way I am hoping to learn a lot more by understanding the process

At the moment I am trying to pass the value of the clicked star

Form

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

JS

$(document).ready(function(){
  $('#firstStar').click(function(){
    $('#hiddenRating').value = 1;
  });
}); 

So the idea is that if a user clicks the first star then a value of 1 should be passed as the ratings value within the form, this does not happen as I do not know what to pass within

:value => ''

Im sure there are much better ways to do this but as i said I want to learn piece by piece so that by the end I can put it all together, of course if someone has a better suggestion then please let me know.

Edit

Controller

def new
  @rating = Rating.new

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @rating }
  end
end

def create
  @rating = Rating.new(params[:rating])

  respond_to do |format|
    if @rating.save
      format.html { redirect_to @rating, notice: 'Rating was successfully created.' }
      format.json { render json: @rating, status: :created, location: @rating }
    else
      format.html { render action: "new" }
      format.json { render json: @rating.errors, status: :unprocessable_entity }
    end
  end
end

Upvotes: 2

Views: 3080

Answers (1)

Richlewis
Richlewis

Reputation: 15374

Ok so hopefully this may help someone else in a similar situatio, my form now looks like this

<%= f.hidden_field :ratings, :id => "hiddenRating"%>#Value has been removed

And my Jquery looks like so

$(document).ready(function(){
 $('#firstStar').click(function(){
  $('#hiddenRating').val(1);
 });
});

There was no need to pass the value within the form as .val() assigns it to the id

That's my understanding anyway

Upvotes: 2

Related Questions