【发布时间】:2017-01-15 23:05:57
【问题描述】:
我正在学习使用 Rails has_many :through 关联。我正在阅读的大部分内容仅提供如何设置模型,而不是如何设置控制器操作。为了学习这个主题,我的应用程序非常基础。我有一个表格,列出了一些垂直行业。创建“垂直”时,有一个选项可以从适用于该垂直的应用程序列表中进行选择(复选框)。创建垂直行业后,应建立垂直行业与所选应用之间的关联。
我有 3 个模型:
class App < ActiveRecord::Base
has_many :solutions
has_many :verticals, through: :solutions
end
class Vertical < ActiveRecord::Base
has_many :solutions
has_many :apps, through: :solutions
end
class Solution < ActiveRecord::Base
belongs_to :app
belongs_to :vertical
end
这是我的表格:
<%= simple_form_for(@vertical) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :name %>
<%= f.input :description %>
<%= f.association :apps, as: :check_boxes %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
这是我的 verticals_controller 创建操作:
def create
@vertical = Vertical.new(vertical_params)
@solutions = @vertical.apps.build(params[:app])
<respond_to code omitted for brevity>
end
def vertical_params
params.require(:vertical).permit(:name, :description, apps_attributes: [ :name, :description, :developer, :mpp, :partner, :website, :app_id[] ])
end
我可以通过这种方式从 rails 控制台创建关联:
vertical = Vertical.first
app = App.first
vertical.apps << app
但我认为这不是在控制器中执行此操作的正确方法,我也不了解如何获取在表单中选择的应用程序参数。我正在寻找一些遵循 Rails 最佳实践的基本、干净的代码示例。另外,如果您能指出我最近的任何解决控制器代码的教程,那就太好了。谢谢。
【问题讨论】:
标签: ruby-on-rails-4 associations