2017-01-15 12 views
0

我正在学习使用Rails has_many:通过关联。我正在阅读的大部分内容仅提供了如何设置模型,但不提供如何设置控制器操作。为了学习这个主题,我的应用程序非常基础。我有一份列出一些垂直行业的表格。创建“垂直”时,可以从适用于该垂直的应用程序列表中进行选择(复选框)。垂直创建时,应该建立垂直和所选应用程序之间的关联。需要简单Has_Many:通过控制器代码

我有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 

我能够从创建协会轨道控制台这种方式:

vertical = Vertical.first 
app = App.first 
vertical.apps << app 

但我不认为这是在控制器中执行它的正确方法,也不了解如何获取在窗体中选择的应用程序参数。我正在寻找一些遵循Rails最佳实践的基本,干净的代码示例。另外,如果你能指点我最近的任何教程,解决控制器代码会很好。谢谢。

回答

0

我能得到通过以下的改变来创建的关联:

在我创建行动在我的控制器:

def create 
    @vertical = Vertical.new(vertical_params) 
    @solutions = @vertical.apps.build 
    <respond_to code omitted for brevity> 
    end 

在我的安全参数,我有以下几点:

def vertical_params 
     params.require(:vertical).permit(:name, :description, app_ids:[]) 
    end 

我不确定这是否完成Rails的最佳实践或不。