Tuesday, September 3, 2013

weblog; Rails views; associations and ajax

Dynamic creation of variables in ruby

    inst_var_name = params[:controller].gsub(/\//, "_").singularize
    instance_variable_set("@#{inst_var_name}", @model)
http://www.funonrails.com/2010/02/dynamic-creation-of-variables-in-ruby.html

How to use dynamic attributes / columns in Squeel statements?

Interesting and has possibilities, but it was taking too much time to figure out a generic approach, so I fell back to typical active record call.

    klass = guess_model_class
    foreign_key_id = "#{klass.reflect_on_all_associations.first.name.to_s}_id"
    @models = klass.find(:all, conditions: ["#{foreign_key_id} = ?", params[foreign_key_id.to_sym]])

Squeel demands that an non-existent variable or method be called so that #method_missing gets called and uses the undefined name to generate sql.

    klass = guess_model_class
    foreign_key_id = "#{klass.reflect_on_all_associations.first.name.to_s}_id"

    # works, but is not generic
    @models = klass.where{new_and_returning_member_progress_id == params[:new_and_returning_member_progress_id]}

    # doesn't work
    @models = klass.where{klass.columns[0] == params[foreign_key_id.to_sym]}

    # doesn't work
    @models = klass.where{table_name.send(foreign_key_id.to_sym) == params[foreign_key_id.to_sym]}
http://stackoverflow.com/questions/12612889/how-to-use-dynamic-attributes-columns-in-squeel-statements

Test if a word is singular or plural in Ruby on Rails

def test_singularity(str)
  str.pluralize != str and str.singularize == str
end
    inst_var_name = params[:controller].gsub(/\//, "_").singularize
http://stackoverflow.com/questions/1801698/test-if-a-word-is-singular-or-plural-in-ruby-on-rails

polymorphic_url: Universal partial

    <div class="well"><%= link_to "Parents", polymorphic_url([@new_and_returning_member_progress, :family, :parents], layout: "none") %></div>
http://apidock.com/rails/ActionController/PolymorphicRoutes/polymorphic_url

No comments:

Post a Comment