代码之家  ›  专栏  ›  技术社区  ›  jonnii

使用嵌套属性表单管理子关系

  •  1
  • jonnii  · 技术社区  · 16 年前

    我想做的是:

    我的模型看起来像这样:

    class Profile < AR:B
        belongs_to :user
    end
    
    class User < AR:B
        has_many :profiles do
            def active
                ...
            end
            def latest
            end
        end
        def profile
            self.profiles.active
        end
    end
    

    最好的管理方法是什么?目前我正在使用:

    accepts_nested_attributes_for :profiles
    

    在用户界面中,但这似乎很有意思。理想情况下,这种逻辑的大部分都会存在于模型中,但我想说的另一件事是使用演示者。

    任何想法都将不胜感激,如果您需要更多信息作为评论,请告诉我,我将适当更新此帖子。

    2 回复  |  直到 16 年前
        1
  •  2
  •   Alessandra Pereyra    16 年前

    也许您应该尝试从用户到配置文件建立两种关系。一个是他们可以通过您的用户界面编辑的,另一个是管理员批准的。

    它可以像这样工作:

    class User < AB:B
    
    has_one :profile #the user-editable one one
    has_one :active_profile, :class_name=>"profile" #the one shown
    
    end
    

    然后,通过表单对用户配置文件所做的每一项更改都会显示给管理员(使用and observer或just and“after_save”过滤器)。当它删除它时,更改将被转储到活动的_profile one,并显示在某个地方。

    这样,您就可以拥有一个干净的表单界面,每当他们再次编辑它时,就会看到最新的(但未经批准的)配置文件。您还可以使用更新的_at列对队列进行排序,以获得“他们的编辑将应用于未完成的配置文件以供审阅,并推送到队列的后面”功能。

        2
  •  1
  •   Nick L    16 年前

    然而,为了处理“待定”配置文件和“批准”配置文件之间的转换,我建议可能添加一个状态机来处理转换。在最近的一个项目中,AASM gem对我来说很好。( http://github.com/rubyist/aasm/tree/master http://github.com/rails/rails/commit/aad5a30bf25d8a3167afd685fc91c99f4f09cc57 )

    您的模型可以如下所示:

    class User < AR:B
    
    has_one :active_profile 
    has_one :pending_profile
    
    include ActiveRecord:: StateMachine
    
    state_machine do
       state :approved
       state :pending
       state :rejected
    
       event :update_profile_pending do
        transitions :to => :pending, :from => [:approved], :on_transition => :send_to_admin_queue
      end
    
       event :update_profile_approved do
        transitions :to => :approved, :from => [:pending], :on_transition => :update_current_profile
       end
    
       event :update_to_rejected do
        transitions :to => :rejected, :from => [:pending]
      end
    end
    
    def send_to_admin_queue
      //method to handlesending pending profiles to admin for approval
    end
    
    def update_current_profile
     //method to handle updated profiles with changes
    end
    
    end
    

    只是个主意!在这里大声思考!