Ruby/Rails: dynamically change attribute in shared partial

This should be a layup for someone...

I'm trying to change a form field's attribute depending on which controller/model is calling the partial containing the form fields...

The issue (below) is with parent_id... which references one of two columns in a dogs table. It needs to either be kennel_id or master_id depending on which view this partial is being rendered in.

Not comfortable enough, yet, with Ruby/Rails language/syntax/tools to dynamically change this without getting bogged down in if/else statements.

I'm calling a shared partial and passing in a local variable:

= render "dogs/form", :parent => @kennel


= render "dogs/form", :parent => @master

In the partial I'd like to:

  = form_for ([parent,]) do |f|
    = render "shared/error_messages", :target => parent

        = f.label :name
        = f.text_field :name
        = f.hidden_field :parent_id  ###  <= PROBLEM
        = f.submit 'Save'


Just thinking out loud:

I don't know if the parent-models have the proper names for it, but you could do something like:

= f.hidden_field "#{}_id"

But that doesn't look right. So, why not pass it as an argument?

= render "dogs/form", :parent => @master, :foreign_key => :master_id

Or, create aliases on the dog model to handle some sort of dynamic delegation:

class Dog
  def parent_id=(parent_id)
    case parent.class
    when Master then self.master_id = parent_id
    when Kennel then self.kennel_id = parent_id
  def parent_id
    case parent.class
    when Master then self.master_id
    when Kennel then self.kennel_id

But that sucks too. Could the relation be polymorphic? Then you can leave out the switching.

class Dog
  belongs_to :owner, :polymorphic => true

= f.hidden_field :owner_id

Just some ideas. Hopefully one of them makes sense to you...

Need Your Help

Error with Grails Executor plugin, bean “persistenceInterceptor” not found

grails asynchronous groovy concurrency executor

I installed the "executor" plugin into my Grails app to do some simple asynchronous processing; I'm not using Hibernate or any fancy persistence. Based on the documentation for the plugin, which ca...

when i run createsuperuser getting HTTP 401 error

python django google-app-engine django-nonrel

Am using Django-nonrel and appengine for my app. user login/logout, user creation everything works fine in local server. But when i try to create remote user it fails with following error.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.