2014-11-23 122 views
0

现有关联我有3种型号:导轨4 - 添加嵌套资源

class Resource < ActiveRecord::Base 
    has_many :blocks 
    has_many :topics, :through => :blocks, dependent: :destroy 

class Topic < ActiveRecord::Base 
    has_many :blocks 
    has_many :resources, :through => :blocks, :class_name => 'Resource', dependent: :destroy 
    accepts_nested_attributes_for :resources 
    accepts_nested_attributes_for :blocks, :allow_destroy => true 

class Block < ActiveRecord::Base 
    belongs_to :resource 
    belongs_to :topic 
    accepts_nested_attributes_for :resource, :allow_destroy => true, :reject_if => :all_blank 

我的路线:

namespace :admin do 
    resources :topics do 
    resources :resources do 
     post :link 
     delete :unlink 

一切正常,只是我想在“添加资源罚款“除了创建一个新的资源(工作正常)之外,还可以选择一个现有资源(在下拉菜单中)。

所以,我想要一个下拉菜单显示所有资源,然后将我选择的一个添加到块模型。换句话说,我只需要创建主题和资源之间的关联(通过Block模型)。

我可以做到这一点,当我有一个多选择,但我打我的头只有一个资源(添加它已被选中)。

我清楚吗? :/

谢谢! - 文森特

回答

0

如果你有一个复杂的逻辑是这样,最好使用一些像 到"Form Objects"保存多个模型和关系他们 之间。即在两种模型之外移动保存逻辑。

access_nested_attributes_for应该仅用于非常非常简单的 情况下(最喜欢的的Rails的神奇功能)