Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
KoRMaK
Jul 31, 2012



Is there a way I can manually execute the validtors that are listed on a model using the validates(*attributes) method?

I can get a list of them using Model.validators, but how would I then easily apply those to the instance I have? I want to skip the ones that use the validates_with clause and only run the ones that do validates(*args) e.g.
Ruby code:
validates :title, presence :true
e: I found a solution here http://stackoverflow.com/questions/3542819/in-rails-3-how-can-i-skip-validation-of-the-password-field-when-im-not-attempt

ee: Here's my current dilema: how do I move this code to a module? Currently this doesn't work.

eee: add included do to the module, this seems to work.
Ruby code:
#module.rb
module FieldValidatorModule
  module Model
    extend ActiveSupport::Concern
    included do
    attr_accessor :system_validations_only
    
    validates_with FieldValidator, :if => Proc.new{ |m| !m.system_validations_only }
    end
  end  
end
Ruby code:
#mymodel.rb
include FieldSettingValidatorModule::Model

KoRMaK fucked around with this message at 16:58 on Nov 15, 2013

Adbot
ADBOT LOVES YOU

KoRMaK
Jul 31, 2012



I'm trying to incoporate facebook login via omniauth with devise. Users can login via facebook, but it broke the regular devise login. I'm getting a wierd error when a user does the ole devise login
Ruby code:
Started GET "/users/sign_in" for 127.0.0.1 
Processing by Devise::SessionsController#new as HTML
  User Load (0.2ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 LIMIT 1
Redirected to [url]http://localhost:3001/dashboard[/url]
Filter chain halted as :require_no_authentication rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.2ms)

Filter chain halted as :require_no_authentication rendered or redirected


I have created a sessions_controller.rb that inherits from Devise::SessionsController but it looks like it is not overriding the gemmed version that comes with devise. How do I override the sessions_controller?

I set the routes for it to this

ruby posted:

devise_for :users, :controllers => {:sessions => "sessions"}

I also have tried overrideing require_no_authentication in the sessions_controller.rb but it never seems to called.

e: drat, I forgot the s in :controllers

KoRMaK fucked around with this message at 18:23 on Nov 19, 2013

KoRMaK
Jul 31, 2012



kayakyakr posted:

What directions are you following for using omniauth with devise? I have a working devise + omniauth (for facebook, google, etc) and I don't have my sessions controller overridden.

The only things I've done is add an ominauth callbacks controller and the configuration to config/initializers/devise.rb
This one http://railscasts.com/episodes/360-facebook-authentication?view=asciicast

It doesn't talk about devise, so I'm filling in those gaps myself and with this gist
https://gist.github.com/schleg/993566

Maybe I should follow this guide https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview

KoRMaK fucked around with this message at 21:19 on Nov 19, 2013

KoRMaK
Jul 31, 2012



Sweet, I have devise and facebook login working side by side. I had to override registrations and sessions to handle the two properly.

New question: how do I keep heroku from taking forever when doing the assets:precompile step? I added ckeditor to my vendor/javascripts folder and I am pretty sure that is what is taking it so long. I never change the files in that directory, so why does it precompile on each push? I want it to only precompile if there are differences.

In case anyone here wants to check out what I've been working on, you can find it at http://marquee.liquid-software.com It lets you create conversation threads connected to any gps location. Kind of like yelp, but instead of being tied to a business you can tie it to any arbitrary location.

KoRMaK
Jul 31, 2012



There were a couple issues I ran into while trying to run my dev environment on windows and I eventually just jumped into running my own linux VM. I'm glad I did it. Linux isn't that scary and the gnome desktop is basically OSX. I like it alot now, and I've learned so much and I was able to learn at my own pace.

KoRMaK
Jul 31, 2012



Yep. That works. From 600 seconds down to 6 seconds. Thanks. Since I'm on heroku I had to add the builder pack to my app.

KoRMaK
Jul 31, 2012



a_big_dog posted:

This is a Rails thread. Surely Heroku is synonymous enough with Rails that discussion of it is worthy of a place in this thread?

I'd think any talk about getting a rails app working on the Internet is appropriate for this thread.

KoRMaK
Jul 31, 2012



prom candy posted:

Yeah and what we're discussing is tricking Heroku into thinking your dyno is active in order to not get it put to sleep. If everyone was to keep their free-tier dynos active at all times they wouldn't be able to offer the free-tier.
I agree, what was described by using new relic is essentially an exploit and would mess up their payment model.

KoRMaK
Jul 31, 2012



I'd like to alter the "rails generate Scaffold MyModel" behavior. I need to make changes to the way models and controllers are spit out in addition to creating some new view files beyond the standard index/form/edit/show. As a plus, it would be nice if I could also alter an existing model to add a relationship clause to the new Scaffold-ed model.

I read this top to bottom http://guides.rubyonrails.org/generators.html#first-contact but it hasn't fully clicked and I can't find an implemented example. I'm looking around in my railities folder and think I probably will copy those files for a start.

I'd like to add this behavior in addition to the default scaffold behavior so I can chose when I want to use it. e.g. rails generate Scaffold and rails generate MyScaffold would both work.

Is this possible?

KoRMaK
Jul 31, 2012



I'm still trying to make my own scaffold generator. For some reason, it cannot find active_record. I have no idea whats going wrong, I've been at this for a couple days. I monkey patched the scaffold_generator and it worked fine. Now I am trying to refactor that to a separate comand so we can scaffold for two different things (generate scaffold MyTest vs generate scaffold_dependency MyTest)

Here are the classes that I copied and customized. These files are all located under lib/generators/* These files were all copied from the railties gem folder and then modified e.g. railties/lib/rails/generators/rails/*

Ruby code:
#require 'rails/generators/rails/resource/resource_generator'
#require 'lib/generators/resource_dependency/resource_dependency_generator'

class ScaffoldDependencyGenerator < ResourceDependencyGenerator #Rails::Generators::NamedBase
  remove_hook_for :resource_controller
  remove_class_option :actions
  
  class_option :stylesheets, :type => :boolean, :desc => "Generate Stylesheets"
  class_option :stylesheet_engine, :desc => "Engine for Stylesheets"
  
  hook_for :scaffold_dependency_controller, :required => true
  
  #hook_for :assets do |assets|
  #  invoke assets, [controller_name]
  #end
  
  #hook_for :stylesheet_engine do |stylesheet_engine|
  #  invoke stylesheet_engine, [controller_name] if options[:stylesheets] && behavior == :invoke
  #end
  
  def add_phrases_to_en
    
    attributes.each do |_attr|
      unless ["account_id", "department_id"].include? _attr.name #build the string of fieldguides to create. exclude account_id and department_id
        _name = _attr.name
        if _attr.reference?
          _name = _name + "_id"
        end
        phrase_string = phrase_string + "\n    #{_name}: \"#{_attr.name.humanize}\""  
    
      end
    end
    
    phrase_string = phrase_string + "\r\n"
    
    #inject the field guide creation statement
    inject_into_file "config/locales/en.yml", :after => /#_auto_generator_hook\s/  do
      phrase_string
    end
               
  end #end add_phrases_to_en
  
  def add_relationship_to_account_model
    inject_into_file "app/models/account.rb", :after => /with_options :dependent => :destroy do \|acc\|/  do
      "\r\n\t\tacc.has_many :#{plural_table_name}"
    end
  end #end add_relationship_to_account_model
    

end

Ruby code:
require 'rails/generators/resource_helpers'
require 'rails/generators/rails/model/model_generator'
require 'active_support/core_ext/object/blank'

#module Rails
  #module Generators
    class ResourceDependencyGenerator < ModelDependencyGenerator #metagenerator
      include Rails::Generators::ResourceHelpers

      hook_for :resource_controller, :required => true do |controller|
        invoke controller, [ controller_name, options[:actions] ]
      end

      class_option :actions, :type => :array, :banner => "ACTION ACTION", :default => [],
                             :desc => "Actions for the resource controller"

      hook_for :resource_route, :required => true
    end
#  end
#end

Ruby code:
#module Rails
#  module Generators
    class ModelDependencyGenerator < Rails::Generators::NamedBase #metagenerator
      argument :attributes, :type => :array, :default => [], :banner => "field[:type][:index] field[:type][:index]"
      hook_for :orm, :required => true
      
      def thing
        Rails.logger.info("\n\n in the model dependency gen\n")
      end
    end
#  end
#end

And in the console, after running scaffold_dependency, all I get are unhelpful errors

Ruby code:
error active_record [not_found]
error resource_rote [not found]
etc...
ModelDependencyGenerator is ran, I can tell because the logger message is in my development.log. But why is it loving up on active_record?

KoRMaK fucked around with this message at 17:24 on Jan 19, 2014

KoRMaK
Jul 31, 2012



How do I join a has_many relationship and order by one of the joined fields?

Here's an example:

@my_thing.persons.includes(:location).order("'persons.role' ASC, 'locations.name' ASC")

The above doesn't work. The sql changes the column names via a "as" call and so the order by clause is effectively useless because person.role and locations.name aren't available.


Uggghh it was a typo. I got too use to making things plural and person.role was typed as person.roles in the order clause.


I'd like to make this the default scope for that relationship on the my_thing model. I tried this but it doesn't work
Ruby code:
has_many :persons, include: :location, :order => "persons.role ASC, locations.name ASC"


Ughhh 2: The has_many declaration works fine. Its the stupid caching we have that was screwing up the render. It didn't think there was any change so it kept showing me the old cached render.

KoRMaK fucked around with this message at 17:24 on Jan 24, 2014

KoRMaK
Jul 31, 2012



Defghanistan posted:

I am sorry to have to post with such a simple question but I've been internetting hard for about 12 hours and cant find a solution that works for me, which is crazy due to how simple of a problem this is.

I have a hash in the form of |k, v| string=>int and I want to get the average of all the int values. That's it.

My closest attempt is:
hash.inject(0) {|total, (k, v)| total + v.last}

But this is returning 'undefined method "last" for fixnum: (last integer value here)'

Can anyone provide me with a quick way of averaging a set of int values? I find it incredibly frustrating that this isn't just a builtin method.

v is already the value you want. No need for v.last, just v

KoRMaK
Jul 31, 2012



Peristalsis posted:

Bummer.

Is there any way to edit or add to what it does? Or another way to force a refresh of the calling page?
I swear I had to deal with something similiar but I kind of forget how. I think it involved using a javascript response. Don't send the file out via the first controller, but instead make the browser ajax request the file in your js response and then you can run a switch in the js response to see if it should do anything else.

KoRMaK
Jul 31, 2012



These are code blocks right? (the failure/succes.html{} bit)

Ruby code:
class ProjectsController < InheritedResources::Base
  def update
    super do |success, failure|
      failure.html { redirect_to project_url(@project) }
      success.html { Rails.logger.info("Success") }
    end
  end
end
https://github.com/josevalim/inherited_resources

I'm using inherited_resources. I've come accross a situation where both my .js and .html responses should be the same. How do I combine them?

Ruby code:
class ProjectsController < InheritedResources::Base
  def update
    super do |success, failure|
      failure.html { redirect_to project_url(@project) }
      success.html { Rails.logger.info("Success") }
      success.js { Rails.logger.info("Success") }
    end
  end
end
Should be

Ruby code:
class ProjectsController < InheritedResources::Base
  def update
    super do |success, failure|
      failure.html { redirect_to project_url(@project) }
      success.html, success.js { Rails.logger.info("Success") }
    end
  end
end
I thought I was close when i did this, but it turns out I was wrong and that my code is just getting run twice and causes double render errors.
Ruby code:
class ProjectsController < InheritedResources::Base
  def update
    super do |success, failure|
      failure.html { redirect_to project_url(@project) }
      [success.html, success.js].each { Rails.logger.info("Success") }
    end
  end
end

KoRMaK
Jul 31, 2012



kayakyakr posted:

try:

Ruby code:
success.all { Rails.logger.info("Success") }
Wow yea that worked. Thank you. How would I have figured this out on my own? What is the success object? An inspect says its a ActionController::MimeResponds::Collector but that doesn't really tell me how I could have figured out that .all would have worked.

edit: oh duh, the help page does inform me of .all http://apidock.com/rails/ActionController/MimeResponds/Collector

Let's say that I want .html and .js to share a response, but .json to return a different thing. What would the statements look like then?

e: Found it down the page here http://edgeapi.rubyonrails.org/classes/ActionController/MimeResponds.html

Ruby code:
success.any(:js, :html) { Rails.logger.info("\n\n Success \n\n") }
OR

Ruby code:
success.all(:js, :html) { Rails.logger.info("\n\n Success \n\n") }

KoRMaK fucked around with this message at 17:54 on Feb 3, 2014

KoRMaK
Jul 31, 2012



kayakyakr posted:

I also believe that it falls through (or fails to do so). So if you have success.json on the first line and then success.all on the second line, it'll respond with the json line and not the all line.

Don't quote me on that, it might cause a double render as well.
Man, now I have a situation where a large portion of the response is the same for both js and html, but the last line differs.

Can I do any magic with that or do I have to build a separate function and call it from each success.whatever call?

KoRMaK
Jul 31, 2012



Just do a website with a three model relationship with jquery plugins, bootstrap, modals, ajax and angular.

KoRMaK
Jul 31, 2012



Ruby code:
success.any(:js, :html) { 
  if success.format.symbol == :js
    Rails.logger.info("\n\n Successful js response \n\n") 
  else
    Rails.logger.info("\n\n Successful whatever else \n\n")  
   end
  }
The above works, the below does not.

Ruby code:
success.any { 
  if success.format.symbol == :js
    Rails.logger.info("\n\n Successful js response \n\n") 
  else
    Rails.logger.info("\n\n Successful whatever else \n\n")  
   end
  }
The format becomes :html for all requests with an unspecific any clause, because why not? Everything is getting treated the same.

KoRMaK
Jul 31, 2012



I have some code that repeats in all of my controller functions, so I'd like to move it to a module as a method. It uses "super" though, and this is where the thing falls apart. How do I pass the "super" method to be invoked by the helper function, or how do I run the edit_helper inline as a proc or something so that "super" makes sense?

Ruby code:
#module
module MyModule
  def edit_helper
    super do |success|
      success.js { render "my/partial", :locals => { :my_local => some_val } }
    end
  end
end

#some controller

  def edit    
    ....
    edit_helper 
    #super do |success|
    #  success.js { render "my/partial", :locals => { :my_local => some_val } }
    #end
  end  

KoRMaK
Jul 31, 2012



Phummus posted:

I'm cross-posting this from the general programming thread:

I am brand new to web development as a whole, and am trying to put together a simple application for patient checkin at work.

I crated a rails scaffold for providers. The model has 4 accessible fields:

Name
Email
Time1
Time2

On the providers/index page, I want to add a button at the end of each row that will populate time2 and keep me on the same page.

So I would have something like:

Name email Time1 Time2 Actions
Fred fred@aol.com 12:00 [Time2]
Joe joe@msn.com 1:00 [Time2]

When the user clicks on the Time2 button, it should populate time2 for that record and then reload/refresh/requery the page to display the new information.

My button on the form is
code:
<%= button_to "Time2", :action => "set_time2" %>
My problems are that I don't know where to define set_time2, and I don't know how to manage the routes so that the user stays on the same page.

Any help?
:remote => true in your links and create js responses for them.

KoRMaK
Jul 31, 2012



Heyyyy, I just learned how to override a column name with a method on Active record and still be able to get the column (db) value.

This causes a stack overflow due to recursion
Ruby code:
def my_items
	_my_items = self.my_items #this calls the function we are already in, I meant to grab the db value instead and erroneously thought that self. would differentiate between the two
	MyItem.find(_my_items)
	_my_items
end
Instead, I meant this:
Ruby code:
def my_items
	_my_items = self[:my_items] #this gets it from the db. also self.read_attribute(:my_items) would work
	MyItem.find(_my_items)
	_my_items
end

KoRMaK
Jul 31, 2012



Has anyone had experience with CanCan? I have class_b which has a relationship to class_a. I want the load_and_authorize_resource call that cancan provides to authorize class_b's actions based on it's relationship to class_a. The documentation for cancan isn't clear about this, and I've tried the :parent and :through methods but it doesn't seem to be right.

KoRMaK
Jul 31, 2012



kayakyakr posted:

1) You should switch to CanCanCan as soon as you are able. CanCan has been abandoned by the creator and taken over by a group of others

2) I don't think you can rely on cancan's auto-load to do that. You might be able to build up a finder that can find the correct authorized classes and that would work.

I would suggest going ahead and loading the resources in a before_action/filter, then calling authorize_resource (layer them in your class so you have:

Ruby code:
class MyClass
  before_action :load_resource
  authorize_resource

  def load_resource
  end
end
In ability.rb, then, you can determine authorization in a block.

poo poo, I had overridden find_resource instead.

KoRMaK fucked around with this message at 18:46 on Apr 17, 2014

KoRMaK
Jul 31, 2012



Here's a more general question, how do I override a method that is used as a prepend_filter?

Instead of doing before_action :load_resource, I'd rather just override the load_resource method from cancan
https://github.com/ryanb/cancan/blob/master/lib/cancan/controller_resource.rb#L29

When I define the method in my controller, it doesn't ever get called. Why is that?

KoRMaK
Jul 31, 2012



kayakyakr posted:

1) You should switch to CanCanCan as soon as you are able. CanCan has been abandoned by the creator and taken over by a group of others

2) I don't think you can rely on cancan's auto-load to do that. You might be able to build up a finder that can find the correct authorized classes and that would work.

I would suggest going ahead and loading the resources in a before_action/filter, then calling authorize_resource (layer them in your class so you have:

Ruby code:
class MyClass
  before_action :load_resource
  authorize_resource

  def load_resource
  end
end
In ability.rb, then, you can determine authorization in a block.

I did the above, and it doesn't seem to work. Can you explain what the flow should be?

Like, how do I get cancan to use the class_a that I loaded to do authing?

KoRMaK
Jul 31, 2012



kayakyakr posted:

authorize_resource checks for an instance variable of the same name as the class. for MyClass it's looking for @my_class or @my_classes (on index) to authorize.

You can override that with
Ruby code:
authorize_resource :my_instance
Also, according to https://github.com/CanCanCommunity/cancancan/wiki/Nested-Resources you can define nested resources as above. Your mileage may vary if you haven't already tried that.

As a reminder, cancan is not compatible with rails 4. most of it works, but some of it is very broken, especially when dealing with relations and how it does its lookups. CanCanCan rectifies some of that breakage.
Thank you. I've taken to going through the gem's lib and found this which backs up what you are saying https://github.com/ryanb/cancan/blob/master/lib/cancan/controller_additions.rb#L145

KoRMaK
Jul 31, 2012



Wow, I just had a small error result in hours of confusion and lost work time.

"Hash.key(:my_key)" is not the same as :Hash.key?(:my_key)"

I knew this, I utilize both a bunch. I just overlooked the "?"

It's kind of nice to feel so young and stupid again.


(the load_resource solution kayakyakr suggested would have worked immediately if I hadn't made that mistake.)

KoRMaK
Jul 31, 2012



Putting simple Logger output messages inside of gems has revealed so much understanding to me and I can't beleive I didn't think to do this sooner. I the reason why I haven't felt comfortable doing it sooner is because I wasn't sure where the folder was and didn't care, and something about the gems folder being sacred and shouldn't be edited.

I've spent all yesterday, some of last night, and this morning debugging CanCan to learn more about why it works the way it does. It has been very enlightening. Just gotta remember to pull my logger messages out and any changes when I'm done. Would a bundle install reset changed gems' files and nuke my changes? Nope, but a gem install -gem_name- will.

KoRMaK fucked around with this message at 15:28 on Apr 18, 2014

KoRMaK
Jul 31, 2012



I have a bunch of Model names that I stored downcased in my DB. So "MyClass" is stored as "myclass" I now need to go the inverse direction, and get the model name so I can constantize it, but I kind of screwed myself because I used downcase ("myclass") instead of underscore ("my_class"). Is there a way I can still find the Model MyClass from the string "myclass" and not "my_class"?

KoRMaK
Jul 31, 2012



Arachnamus posted:

Just iterate through the model filenames on the filesystem and find matches in the DB, then correct the DB entries to be something more useful. Or do them by hand, surely there's not that many?
There's like 20 model names, each with guides that use them and then an arbitrary amount that rely on that. Upgrading the db stored downcased values would probably be a bad idea, regression testing would involve the whole app.

Creating a map would be good though. Since they are all ActiveRecord descendants I could do this ActiveRecord::Base.descendants or loop through the file system as suggested.

KoRMaK
Jul 31, 2012



Smol posted:

Search for matching constants with Module.constants.
This method didn't work at first while I was working in console, then I did this
Ruby code:
Rails.application.eager_load!
ActiveRecord::Base.descendants.each{ |k| puts k }
And thought "maybe I should try smol's suggestion again" and it spit out all the constnats I was looking for. It's the eager_load! that needs to happen. The AR::Base way narrows down results and still contains what I need. Thanks err' body!

KoRMaK
Jul 31, 2012



So the purpose of this was to dynamically reflect a fields requiredness to the user on forms. Our app also allows users to select any field to be required, but hadn't integrated a way to reflect the model level requirements (validates presence stuff).

Now we can reflect both to the user! Lame, but exciting. Rails is fun.

KoRMaK
Jul 31, 2012



Is there a way to make a two sided polymorphic join table?

The join table would be:
object_id
object_type
related_item_id
related_item_type

KoRMaK
Jul 31, 2012



Oh, derp, I can probably get this done with using as: on the object side. I've figured something similar to this out before, it's just a little hazy remembering the nuances of the has many options. The one I always forge is that as defines the column name you want the current object to masquarde as.

KoRMaK
Jul 31, 2012



I have a custom getter/setter that I want to run through validator using

validates :field, :format => {my_options}

But the statement seems to ignore the validator. Is there a way to bridge the built-in validates feature with my own custom getter/setter?

KoRMaK
Jul 31, 2012



fruition posted:

Took me literally 10 hours to figure out how to clean install Ruby on Rails, Git, and Heroku on Ubuntu. The learning curve apparently starts before you even get your environment setup. There's just too many outdated guides and poo poo, I may be a retard but I feel like it should be easier to setup.
If you've never used those tools before, then yea. That's typical for technical skills.

KoRMaK
Jul 31, 2012



In a view, I'm doing some caching

Ruby code:
<% cache ['my_view', obj] do %>
Problem is, when obj is a custom class I wrote I get nil exception errors. Another custom class I wrote works fine, but this one in particular does not. I added a cache_key method to my custom object, and it doesn't ever get hit. What am I missing?

KoRMaK
Jul 31, 2012



KoRMaK posted:

In a view, I'm doing some caching

Ruby code:
<% cache ['my_view', obj] do %>
Problem is, when obj is a custom class I wrote I get nil exception errors. Another custom class I wrote works fine, but this one in particular does not. I added a cache_key method to my custom object, and it doesn't ever get hit. What am I missing?
I did some more tracking on this, and the cache_key is being ran on the containing hash (obj is a hash). I dived into the rails library and found out that it is going wrong somewhere with calling hash.to_param. Being able to go into rails source code and just put debugger statements helps so much :aaa:

KoRMaK
Jul 31, 2012



I'm using url_for on an object that has an :as clause in it's route. The proper helper is "myscope_mymodel_path"

code:
    resources :mymodel, :as => "myscope_mymodel"
but url_for only uses the helper path "mymodel_path" and as such my app crashes because there is no helper for that, it is actually "myscope_mymodel_path". How do I get url_for to be smarter and use the right helper? I'm using this with other objects that don't have the myscope prefix, so it needs to be dynamic.

Adbot
ADBOT LOVES YOU

KoRMaK
Jul 31, 2012



I wrote a module and a helper to figure this out. the Module goes on the object and enables it to respond to a method that returns it's nested route prefix. The helper figures out if it should turn that into a [:prefix, @item] array or if just @item will suffice.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply