I have User Model and Car Model.
I show a add button in the cars/index.html.erb for every Car so that a User can add any Car he want. And in the users/show.html.erb i want to list all the Cars he added.
The Problem is, it connect not only the clicked Car to the User, but also all other cars in the cars/index.html.erb.
user.erb and car.erb
class User << ActiveRecord::Base
has_many :cars
end
class Car << ActiveRecord::Base
belongs_to :user
end
cars/index.html.erb
<% @car.each do |car| %>
#...
<td><%= link_to 'Get Car', '#', :onclick => get_car(car.id) %></td>
#...
<% end %>
cars_helper.rb
def get_car(id)
current_user.cars << Car.find_by(id: id)
end
user/show.html.erb
<% if @user.cars.any? %>
<% @user.cars.each do |c| %>
<%= c.name %>
<% end %>
Aucun commentaire:
Enregistrer un commentaire