在选择框中将记录添加到“ has_and_belongs_to_many”联接表中

时间:2018-10-11 04:50:13

标签: ruby-on-rails ruby ruby-on-rails-5

我有两个具有has_and_belongs_to_many关系的模型,rentalproject

 class Rental < ApplicationRecord
    has_and_belongs_to_many :deals
 end

 class Project < ApplicationRecord
     has_and_belongs_to_many :rentals
 end

Rentals具有一个show.html.erb页面,该页面是公开的,并且是根据有关公寓租金的数据(例如localhost:3000/rentals/1)预先植入的。用户登录后,我希望他们将他们正在查看的Rental(例如id:1)添加到特定的Project。我观看了railscast并建立了关联。

建立与用户关联的所有Projects的选择框以显示在Rental show.html.erb页上并将记录添加到{{1}的最佳方法是什么}和Rental JoinTable吗?应该有一些Controller和View工作,但是我无法将记录发布到该Rentals Projects JoinTable。

编辑,我想出了一个解决方案

我最终要做的是以下事情:

1)在视图中,使用包装在表单标签中的options_from_collection_for_select,:method =>:patch给了我选项

2)在“路由”文件中,我创建了一个新条目,用于在视图中引用的Project资源:

rentals

和3),在Rentals Controller中,将以下内容添加到新方法 resource :rentals member do patch 'add_to_project' end end 中,该新方法从视图的选择框中获取了项目的选项ID,并通过以下方式将其添加到集合中:

project.rentals <<出租

感谢大家的帮助!

0 个答案:

没有答案