简体   繁体   中英

Adding a new Favorite: Creating a form with the current_user.id

I'm trying to create a form that will save the current_user.id. Something is funky in my controller. Any thoughts on obvious issues?

View (new.html.erb)

<!-- Label and input for user_id -->
  <div class="form-group">
    <label for="user_id" class="control-label">
      User
    </label>
    <%= current_user.id %>
    <input type="hidden" name="user_id" value="<%= current_user.id%>">
  </div>

Controller (favorites_controller.rb)

def create
@favorite = Favorite.new
@favorite.dish_comment = params[:dish_comment]
@favorite.user_id = curent_user.id
d = params[:dish_id]
r = params[:restaurant_id]

problem code:

@favorite.user_id = curent_user.id

I thing you should put an @ in front of your current_user to make it accessible in the ERB and in the controller.

Plus, once you save the current_user, you should user params[:user_id] to match the erb (input name is user_id).

Please look at the rails server output, it will tell you what parameters are submitted in the request.

Thanks @jackhaskeyboard. I spelled "current" wrong.

I'm now getting the following errors: Add Favorite Error Messages 1. "User has already been taken" -A user should be able to post unlimited favorites, so I"m not sure why this is occurring.

  1. "Dishing can't be blank" -The purpose of this form is to select two variables (dish & restaurant), search the dishing join table to see if that combination exists. If not, create one, if so, grab the dishing_id, and use it to create a new favorite entry (user & dish/restaurant)

Here's my view code:

<div class="row">
<div class="col-md-12">
<form action="/create_favorite" method="post">
  <!-- Hidden input for authenticity token to protect from forgery -->
  <input name="authenticity_token" type="hidden" value="<%= form_authenticity_token %>">

  <!-- Label and input for user_id -->
  <div class="form-group">
    <% current_user.id %>
    <input type="hidden" name="user_id" value="<%= current_user.id%>">
  </div>

  <!-- Label and input for dishing_id -->
  <div class="form-group">
    <label for="dishing_id" class="control-label">
      Dish
    </label>
    <%= select_tag(:dish_id, options_from_collection_for_select(Dish.all, 'id', 'dish_name')) %>
  </div>

  <!-- Label and input for restaurant_id -->
  <div class="form-group">
    <label for="restaurant_id" class="control-label">
      Restaurant
    </label>
    <%= select_tag(:restaurant_id, options_from_collection_for_select(Restaurant.all, 'id', 'name') ) %>
  </div>

<button class="btn btn-success">
    Create Favorite
  </button>
  or
  <a href="/favorites">Cancel</a>
</form>
</div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM