如何通过onclick连接Rails中的两个现有对象



我有用户模型和汽车模型
我在cars/index.html.erb中为每辆车显示了一个添加按钮,这样用户就可以添加他想要的任何车。在users/show.html.erb中,我想列出他添加的所有汽车
问题是,它不仅将点击的汽车连接到用户,还将汽车/index.html.erb.中的所有其他汽车连接到


user.erb和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 %>

类似这样的东西:

cars/index.html.erb

<% @car.each do |car| %>
#...
  <%= link_to 'Get Car', get_car_path(:id => car.id)   %>
#...
<% end %>

cars_controllers.rb

def get_car
  @user = current_user
  @user.cars = Car.find(params[:id])
  respond_to do |format|
    if @user.save
      format.html { redirect_to cars_url }
      format.json { head :no_content }
    end
  end 
end

routes.rb

match '/cars/get_car' => 'cars#get_car', :as => :get_car 

最新更新