【问题标题】:Displaying sublass model name in Rails form helper shared by subclasses在子类共享的 Rails 表单助手中显示子类模型名称
【发布时间】:2011-07-17 19:50:35
【问题描述】:

鉴于这些模型:

class Person
end

class Man < Person
  def edit 
    @person     = Man.find(params[:id])

    respond_to do |format|
      format.js { render :template => "man_form" } }
    end
  end
end

class Woman < Person
  def edit 
    @person     = Woman.find(params[:id])

    respond_to do |format|
      format.js { render :template => "woman_form" } }
    end
  end
end

然后在每个表单中,我使用这个由所有人共享的辅助方法创建一个“特征”的“选择”:

def person_select(person, options)
  select :person, "characteristics", options
end

我将如何做到这一点,以便当它被一个子类(男人或女人)调用时,它会创建具有该模型名称的选择名称,而不是父“人”?

所以,我希望能够打电话:

person_select(@man_object, {...})

然后得到:

<select name="man[age]" id="man_age">
...
</select>

我需要这样做的原因是,当提交表单时,我可以从 man_controller 获取 params[:man] 或从 woman_controller 获取 params[:woman] 并能够使用这些特定的对象类型,并且不是“人”。

我可以获得类名并执行以下操作: 选择 person.class.to_s.underscore 但它不再使用该对象,因此不会在列表中选择传递的对象。

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 inheritance


    【解决方案1】:

    您可以询问它属于哪个类,然后调用该类的名称。

    $ Post.first
    => #<Post id: 1>
    $ Post.first.class
    => Post(id: integer, title: string)
    $ Post.last.class.name
    => "Post"
    

    让我困惑的是你有一个@man_object,所以很明显这个对象是一个男人,这意味着你可以只有两个助手假设你也会有一个女人对象:

    man_select(@man_object, {...})
    woman_select(@man_object, {...})
    

    然后是你的select_fields

    def man_select(person, options)
      select_tag :man, "characteristics", options
    end 
    
    def woman_select(person, options)
      select_tag :woman, "characteristics", options
    end
    

    但如果你不知道是男是女:

    man_select(@person, {...})
    

    然后是你的 select_tag:

    def person_select(person, options)
        if person.class.name = "Man"
            select_tag :man, "characteristics", options
        else
            select_tag :woman, "characteristics", options
        end
    end
    

    【讨论】:

    • 但是它没有对象,所以如果它处于编辑模式,它不会使该对象在列表中被选中。我也会编辑帖子以说明这一点。
    • 如果你有一个@man_object,为什么你需要知道它是否是一个Man?这不是暗示吗?
    • 你能从概念上解释你想要做什么吗?
    • 或者更好地提供代码来解释您如何获取person 对象。比如你的数组,或者其他什么。
    • 好的,我用你想要的信息更新了帖子。谢谢。
    猜你喜欢
    • 2022-01-23
    • 1970-01-01
    • 2012-12-15
    • 2016-09-25
    • 2016-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多