Nested forms in rails 4 and the fields_for method Posted: 13 Apr 2016 07:00 AM PDT I am also having problems with nested forms and Rails 4 (this seems to be quite common unfortunately). I have events which have requirements, the models are: class Event < ActiveRecord::Base enum type: [:lecture, :exercise, :tutorial] has_one :requirement, dependent: :destroy #accepts_nested_attributes_for :requirement end and class Requirement < ActiveRecord::Base belongs_to :event end There is essentially a one-to-one correspondence between those two. Now I would like to create a new event together with the associated requirement. I am using the following form: <div class="container"> <%= form_for(@event) do |f| %> <% if @event.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@event.errors.count, "error") %> prohibited this event from being saved:</h2> <ul> <% @event.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="container"> <%= f.select :type, Event.types.map { |key, value| [key.humanize, key] }%> <%= f.text_field :number, placeholder: "1298035" %> <% f.fields_for :requirement, @event.requirement do |fields| %> <%= fields.check_box :beamer %><br /> <% end %> <%= f.submit %> </div> <% end %> </div> As you can see I would like to have a checkbox indicating whether a beamer is required. The problem is that the fields_for block is never evaluated. Similar to these posts: Rails 3: fields_for showing blank filed on Edit view Helper "fields_for" not working As far as I can tell the objects are created properly: # GET /events/new def new @event = Event.new @event.build_requirement end If I use puts I see that both objects are not nil and that the associations are correct. I am kind of new to rails and I must say that I'm stymied. Any ideas? |
Rails timestamps, See how much time passed since last time Posted: 13 Apr 2016 07:00 AM PDT In my app I want to print out the duration of time I spent from I made the model until I updated it. So if I have the value :created_at set to 2016-04-13 14:00:49 UTC and :updated_at set to 2016-04-13 15:05:49 UTC I want to print out that it took 1hour and 5minutes. (or just 01.05). How do I do this? |
Ruby-Saml Certificate issue Posted: 13 Apr 2016 06:56 AM PDT I am not sure if I am doing something wrong here but I've been stuck on this issue for quite some time. I am using the Ruby-saml gem (https://github.com/onelogin/ruby-saml) and I am not sure if my settings.certificate is valid. I used OpenSSL to generate the public/private key pair. Here is my public key: $ cat cert.pem -----BEGIN CERTIFICATE----- MIIE3zCCA8egAwIBAgIJANtTrhs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ZXcgWW9y azEPMA0GA1UEBxMGSXRoYWNhMRswGQYDVQQKExJDb3JuZWxsIFVuaXZlcnNpdHkx DjAMBgNVBAsTBUR5c29uMSMwIQYDVQQDExpjdW1pbm9ycy5keXNvbi5jb3JuZWxs LmVkdTEgMB4GCSqGSIb3DQEJARYRbm1jNTJAY29ybmVsbC5lZHWCCQDbU64bKu5p JjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQBA8QEvcxLnjZURGb5/ a4JUVwU6noFdZpmI9FgBi7d3nKs+BNxL/1Het6Kk19T1kPlyDdG96asG6fbRH24G cJOoDvVpx6lxMu85gFpJVv/vtDmnlpiBoDH+v2I7O4ENhve76B7Z5XtT5FsjEdy4 RAn1iczxq391vFNQJl0kCz2Khdv5CS3t6qNS42sPcRk9mjbnN0wz6jHxG5BfCVdk dXxoLuJVLzT7/sbBkT2SLkwQkPiYitb3LFoNFu+Sk8y+L4cVaeoA5XoEjmIbtkgD oLCrILf6t18C/R2AD0/huq2pFtxd/rng/yGMniTBc6aGDsv06RXo/5r7DsO0feXV cRzc -----END CERTIFICATE----- In Rails I tried multiple different way to get this to work: settings.certificate = "-----BEGIN CERTIFICATE----- MIIE3zCCA8egAwIBAgIJANtTrhsq7mkmMA0GCSqGSIb3DQEBBQUAMIGlMQswCQYD VQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxDzANBgNVBAcTBkl0aGFjYTEbMBkG A1UEChMSQ29ybmVsbCBVbml2ZXJzaXR5MQ4wDAYDVQQLEwVEeXNvbjEjMCEGA1UE AxMaY3VtaW5vcnMuZHlzb24uY29ybmVsbC5lZHUxIDAeBgkqhkiG9w0BCQEWEW5t YzUyQGNvcm5lbGwuZWR1MB4XDTE2MDQxMjE4MTUzOVoXDTI2MDQxMDE4MTUzOVow gaUxCzAJBgNVBAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazEPMA0GA1UEBxMGSXRo YWNhMRswGQYDVQQKExJDb3JuZWxsIFVuaXZlc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xq391vFNQJl0kCz2Khdv5CS3t6qNS42sPcRk9mjbnN0wz6jHxG5BfCVdk dXxoLuJVLzT7/sbBkT2SLkwQkPiYitb3LFoNFu+Sk8y+L4cVaeoA5XoEjmIbtkgD oLCrILf6t18C/R2AD0/huq2pFtxd/rng/yGMniTBc6aGDsv06RXo/5r7DsO0feXV cRzc -----END CERTIFICATE-----" I've also tried to just have Rails read the cert.pem file directly: settings.certificate = OpenSSL::X509::Certificate.new(File.read("#{Rails.root}/cert.pem")).to_s The issue is (which I am not sure is an issue), my key is a long inline string in the XML file (metadata for the SP) <md:KeyDescriptor use="encryption"> <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> <ds:X509Data> <ds:X509Certificate> MIIE3zCCA8egAwIBAgIJANtTrhsq7mkmMA0GCSqGSIb3DQEBBQUAMIGlMQswCQYDVQQGEwJVUzERMA8GA1UECBMITmV3IFlvcmsxDzANBgNVBAcTBkl0aGFjYTEbMBkGA1UEChMSQ29ybmVsbCBVbml2ZXJzaXR5MQ4wDAYDVQQLEwVEeXNvbjEjMCEGA1UEAxMaY3VtaW5vcnMuZHlzb24uY29ybmVsbC5lZHUxIDAeBgkqhkiG9w0BCQEWEW5tYzUyQGNvcm5lbGwuZWR1MB4XDTE2MDQxMjE4MTUzOVoXDTI2MDQxMDE4MTUzOVowgaUxCzAJBgNVBAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazEPMA0GA1UEBxMGSXRoYWNhMRswGQYDVQQKExJDb3JuZWxsIFVuaXZlcnNpdHkxDjAMBgNVBAsTBUR5c29uMSMwIQYDVQQDExpjdW1pbm9ycy5keXNvbi5jb3JuZWxsLmVkdTEgMB4GCSqGSIb3DQEJARYRbm1jNTJAY29ybmVsbC5lZHUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCnVjE8GIJe19Ba+361+c7ATDhBrzpGQoe+IDrDWw8B68HayaAvC8PqWdNQNQ3SfHOdb+Vv0eywxHG7wRVVrJ+f8fLqmHBHfthzRG1JnGhReUXb/+wfkUEwDFZPEnEcj6rBcSbX5nsLVvupMXw43XB7ev/NX1SLsRU4trS25YMOozxjL+SfcKsWIQPgqD3usIArwS6b3UQ+ftuVfmWqKEqoUq25tUXoAporFkJyVqXZqe4g/Q+WqbX4cD9e1u7q8OlbSeVXUyPwRsNXzn1n+8tUbCc2k8+glEW5UJk7DY0AP95ry0ZcpfLrkgaOTqvbkUWCaZH1FP04SYG5Csw/8IDtAgMBAAGjggEOMIIBCjAdBgNVHQ4EFgQUq3ybbMNZOEXWgJ7/K0mSMx3VeTMwgdoGA1UdIwSB0jCBz4AUq3ybbMNZOEXWgJ7/K0mSMx3VeTOhgaukgagwgaUxCzAJBgNVBAYTAlVTMREwDwYDVQQIEwhOZXcgWW9yazEPMA0GA1UEBxMGSXRoYWNhMRswGQYDVQQKExJDb3JuZWxsIFVuaXZlcnNpdHkxDjAMBgNVBAsTBUR5c29uMSMwIQYDVQQDExpjdW1pbm9ycy5keXNvbi5jb3JuZWxsLmVkdTEgMB4GCSqGSIb3DQEJARYRbm1jNTJAY29ybmVsbC5lZHWCCQDbU64bKu5pJjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQBA8QEvcxLnjZURGb5/a4JUVwU6noFdZpmI9FgBi7d3nKs+BNxL/1Het6Kk19T1kPlyDdG96asG6fbRH24GcJOoDvVpx6lxMu85gFpJVv/vtDmnlpiBoDH+v2I7O4ENhve76B7Z5XtT5FsjEdy4RAn1iczxq391vFNQJl0kCz2Khdv5CS3t6qNS42sPcRk9mjbnN0wz6jHxG5BfCVdkdXxoLuJVLzT7/sbBkT2SLkwQkPiYitb3LFoNFu+Sk8y+L4cVaeoA5XoEjmIbtkgDoLCrILf6t18C/R2AD0/huq2pFtxd/rng/yGMniTBc6aGDsv06RXo/5r7DsO0feXVcRzc </ds:X509Certificate> </ds:X509Data> </ds:KeyInfo> </md:KeyDescriptor> The IdP people said it was not valid when they tried to use it, he gave me an example of theirs and theirs was split across many lines unlike mine which is just a long string with no space: https://shibidp.cit.cornell.edu/idp/shibboleth Am I doing something wrong here? All I did was take the output from cat and pasted it to my SAML Settings. |
Why isn't my acts as votable working? Posted: 13 Apr 2016 06:59 AM PDT When I click upvote I get an error enter image description here Heres my routes.rb Rails.application.routes.draw do #root 'pages#index' resources :posts devise_for :users # Define root URL root 'pages#index' # Define roots for pages get '/home' => 'pages#home' get '/user/:id' => 'pages#profile' get '/explore' => 'pages#explore' resources :posts do member do put "like", to: "posts#upvote" # maybe change it to POSTS?? put "dislike", to: "posts#downvote" # maybe change it to POSTS?? end end And my posts_controller.rb class PostsController < ApplicationController #resources posts def new @post = current_user.posts.build end def index @post = Post.all end def show @post = Post.find(params[:id]) end def create @user = User.find(session[:user_id]) @post = current_user.posts.build(permit_post) if @post.save flash[:success] = "Uploaded" redirect_to '/' else flash[:error] = @posts_errors_full_messages end end def upvote1).exists? current_user = User.find_by_id(session[:user_id]) @post = Post.find(params[:id]) current_user.upvotes @post redirect_to :back end def downvote @post = Post.find(params[:id]) @post.downvote_by current_user redirect_to :back end private def permit_post params.require(:post).permit(:image, :title); end end And I have in my index <%= link_to like_post_path(@post), method: :put, class: 'upvote' do %> In the URL its showing myurl.com/posts/%23/like I think this means its not getting the id, how can I fix it? This is literally exusting me, thanks in advance |
Set Variables like current_user in Application Controller Posted: 13 Apr 2016 06:56 AM PDT I have the following Base Controller for Brands Scope class Brand::ApplicationController < ApplicationController before_action :authenticate_brands_member! before_action :current_company helper_method :current_company private def current_company current_brands_member? current_brands_member.company : nil end end The variable current_brands_member is the device model for authentication for members . Each Member belongs to a Company members(id, name, company_id,...) companies(id, name, ....) brands(id, name, company_id,...) Since i will be traversing through members to companies to brands i want to set a common variable current_company which will have the content of the member's company when required in the controllers and views. When i try to access the same in the controller like this class Brands::MembersController < Brand::ApplicationController def index puts current_company.inspect end end Am getting the following error undefined local variable or method `current_company' for #<Brands::MembersController:0x007f90c34a8138> |
How to search through nested has_many through? Posted: 13 Apr 2016 07:00 AM PDT Here what I have now : class Pokemon < ActiveRecord::Base has_many :pokemon_moves, dependent: :destroy has_many :moves, through: :pokemon_moves end class PokemonMove < ActiveRecord::Base belongs_to :pokemon belongs_to :move end class Move < ActiveRecord::Base belongs_to :type end And many others, no important. I just would like to search for a Pokémon which could have Move named "pound" and another Move "mega-punch" I tried : Pokemon.joins(:moves).where(moves: {name: 'pound'}).where(moves: {name: 'mega-punch'}) But no result. The translated SQL is : SELECT "pokemons".* FROM "pokemons" INNER JOIN "pokemon_moves" ON "pokemon_moves"."pokemon_id" = "pokemons"."id" INNER JOIN "moves" ON "moves"."id" = "pokemon_moves"."move_id" WHERE "moves"."name" = $1 AND "moves"."name" = $2 [["name", "pound"], ["name", "mega-punch"]] If I only search for one move, it works just fine, but I can't get it with two moves. I have tried many things, but all concludes to bad results. Of course, I have a Pokémon that have those moves, if I do Pokemon.find_by_name('golurk').moves I can retrieve those two moves. Thanks ! |
Basic Rails syntax : can we do a a = b || c in rails ? Posted: 13 Apr 2016 06:59 AM PDT I found a lot of questions about this : a ||= b but this is not my question. I would like to know if we can do a "if first is null then choose second" ? foo = bar || doe #if bar is nil, foo = doe |
Change one model of ActiveRecord:Relation with iterator and then return as Relation Posted: 13 Apr 2016 06:50 AM PDT I have a Relation instance called listings_relation including several listings. I wanna run a method for each listing and keep the result as Relation class , rather than Array. The method would change the listing(not only update) itself somehow so that I don't use update. Due to this, each and map are not fit for me. def foo listings_relation.each {|listing| listing.bar} #each would return listings_relation but without change. end def foo listings_relation.map {|listing| listing.bar} #map would return Array instance with change. #I want Relation instance and it should be changed. end Best Regards! |
Render template in other view with another controller Posted: 13 Apr 2016 07:00 AM PDT How Can I render template with other controller to another view? I want generate 'index' template in modal, but this modal is generated in other view with other controller. So I must create objects in controller which must be setted for other 'index' action. |
How to counter multiple accounts from same user because of Auth Providers Posted: 13 Apr 2016 06:54 AM PDT I have implemented Auth providers (twitter, facebook, soundcloud) for an app(ruby on rails) but the constraint i have in place so that no new User accounts are created is based on email, but some providers do not provide email address. Whats a good counter measure to avoid creating multiple accounts for same user? user.model class User < ActiveRecord::Base has_many :usertracks, :dependent => :destroy mount_uploader :image, ArtistPhotoUploader TEMP_EMAIL_PREFIX = 'change@me' TEMP_EMAIL_REGEX = /\Achange@me/ # Include default devise modules. Others available are: # :lockable, :timeoutable devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable validates_format_of :email, :without => TEMP_EMAIL_REGEX, on: :update validates_presence_of :image validates_integrity_of :image validates_processing_of :image def self.find_for_oauth(auth, signed_in_resource = nil) # Get the identity and user if they exist identity = Identity.find_for_oauth(auth) user = signed_in_resource ? signed_in_resource : identity.user # Create the user if needed if user.nil? UsersController.finish_signup email_is_verified = auth.info.email && (auth.info.verified || auth.info.verified_email) email = auth.info.email if email_is_verified user = User.where(:email => email).first if email # Create the user if it's a new registration if user.nil? firstname = auth.info.name.split(' ')[0] surname = auth.info.name.split(' ')[1] user = User.new( firstname: firstname, surname: surname, #username: auth.info.nickname || auth.uid, email: email ? email : "#{TEMP_EMAIL_PREFIX}-#{auth.uid}-#{auth.provider}.com", password: Devise.friendly_token[0,20], remote_image_url: auth.info.image.gsub('http://','https://') ) user.oauth_token = auth.credentials.token user.oauth_secret = auth.credentials.secret user.skip_confirmation! user.save! end end # Associate the identity with the user if needed if identity.user != user identity.user = user identity.save! end user end def email_verified? self.email && self.email !~ TEMP_EMAIL_REGEX end end |
undefined method `include?' for nil:NilClass ruby gem Posted: 13 Apr 2016 06:57 AM PDT undefined method `include?' for nil:NilClass Goal.rb Here is my steps controller. class Goal def self.gaming? gaming w = gaming["description"] w.include?("AMD") end def self.ssd? ssd w = ssd["description"] w.include?("SSD") end def self.hdd? hdd w = hdd["description"] w.include?("HDD") end def self.hd? hd w = hd["description"] w.include?("FULL HD") end def self.value_of p {"game" => Goal.gaming?(p), "ssd" => Goal.ssd?(p),"hhd" => Goal.hdd?(p),"Full HD" => Goal.hd?(p)} end end index.html.erb <h1>Lachesschoc catalog</h1> <% @products.each do|p| %> <li> <p>Name: <%= p["name"] %></p> <p>Price: <%= p["display_price"] %></p> <p>Description: <%= p["description"] %></p> <p>Properties: <%= p["product_properties"] %></p> <p>Classifications: <%= p["classifications"] %></p> <p>Value_of: <%= Goal.value_of(p)%></p> </li> <% end %> Let me know if you need any other parts added to the question. Thanks in advance. |
Read-Only; and Read-And-Write Abilities for CanCan in Rails UI Posted: 13 Apr 2016 06:30 AM PDT I'm working with a large list of abilities for users with different Role types on a rails application. This is with the CanCan gem. It has gotten quite large, and I have non-dev users who want to be able to see a run-down of abilities for different users. How can I represent the existing abilities on a user interface? i.e. class MyUserAbilityController < ActionController::Base def show @abilities = current_user.abilities end def index @full_abilities = Hash.new Role.all.each do |role| @full_abilities[role.name] = role.abilities end end end And then pass it along to the view? Further, although not necessary, is there a way I can dynamically change or alter the CanCan abilities from an external source? I have been playing around with it in the Terminal for now, with an eventual goal to be able to have some basic rule-setting (not creation, but perhaps changing 'can's to 'cannot's) on an admin user interface with radio buttons. -Schwad |
Simple form with ajax inside form_tag Posted: 13 Apr 2016 06:28 AM PDT I have this view. It have a form_tag and show values on table and inside table I have a simple_form_for and a input field. When I digit a value this input I click on button "Save value" and after I save this value on my table Authorization. This operation is for AJAX because I have a other button "Reverse" more below. How I can do it? I read the rails doc, in AJAX part, but what I want is more specific. My view this it: <%= form_tag(new_refinancing_path, name: 'form', method: :get) do %> <% @employees.each do |employee| %> <table class="table table-condensed"> <tr> <th>Name</th> <td><%= employee.person.name %></td> </tr> </table> <table class="table table-condensed table-bordered table-hover"> <thead> <th> </th> <th>Contract number</th> <th>Value to Solve</th> </thead> <tbody> <% @authorizations.each do |authorization| %> <tr> <td><%= check_box_tag 'authorization[contract_ids][]', authorization.contract_number %></td> <td><%= authorization.contract_number %></td> <td><%= number_to_currency authorization.total_value %></td> <td> <%= simple_form_for(@authorization, remote: true) do |f| %> <%= f.input :value_solve, label: false, placeholder: "Digit a value" %> <%= f.submit 'Save value' %> <% end %> </td> </tr> <% end %> </tbody> </table> <% end %> <%= submit_tag "Reserve", :class => 'btn btn-primary btn-reserva' %> <% end %> And my controller, I can do it? respond_to do |format| if @authorization.save format.js { 'do something' } end end |
Editing the hba_file using postgresql in rails Posted: 13 Apr 2016 06:15 AM PDT I have installed postgresql as a database in my rails app. I am having trouble configuring the database. I followed stack overflow posts and figured out how to create a user and create databases. The problem is authenticating the user. I know that involves configuring the hba_file; I ran the following command to open the config file. sudo vi /etc/postgresql/9.3/main/pg_hba.conf I know I have to edit the following line in the hba_file . I need to change peer to md5. # Database administrative login by Unix domain socket local all postgres peer I have found the file but I am having a lot of trouble editing the file. I press I to insert/edit new values. I don't know how to save the file. I closed the terminal and opened the file again. I get the following error. E325: ATTENTION Found a swap file by the name "/etc/postgresql/9.3/main/.pg_hba.conf.swp" owned by: root dated: Wed Apr 13 01:26:42 2016 file name: /etc/postgresql/9.3/main/pg_hba.conf modified: YES user name: root host name: kpauls-scorecliq-2942283 process ID: 32423 While opening file "/etc/postgresql/9.3/main/pg_hba.conf" dated: Wed Mar 16 04:06:59 2016 (1) Another program may be editing the same file. If this is the case, be careful not to end up with two different instances of the same file when making changes. Quit, or continue with caution. (2) An edit session for this file crashed. If this is the case, use ":recover" or "vim -r /etc/postgresql/9.3/main/pg_hba.conf" to recover the changes (see ":help recovery"). If you did this already, delete the swap file "/etc/postgresql/9.3/main/.pg_hba.conf.swp" to avoid this message. Swap file "/etc/postgresql/9.3/main/.pg_hba.conf.swp" already exists! [O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort: I am not sure how to edit the hba_file file and save the changes. I understand how to create users and creating databases. However, I am having a very hard time editing the file. I am not sure how to edit and save the file. I read several posts on stack regarding this topic but they don't really explain how to edit the file. Any help regarding this would be greatly appreciated. Thanks!! |
Implement an efficient slack-like subdomain name suggestion Posted: 13 Apr 2016 06:50 AM PDT I have a Rails app with PostgreSQL. I'm trying to implement a method to suggest alternative names for a certain resource, if the user input has been already chosen. My reference is slack: Is there any solution that could do this efficiently? For efficiently I mean: using only one or also a small set of queries. A pure SQL solution would be great, though. My initial implementation looked like this: def generate_alternative_names(model, column_name, count) words = model[column_name].split(/[,\s\-_]+/).reject(&:blank?) candidates = 100.times.map! { |i| generate_candidates_using_a_certain_strategy(i, words) } already_used = model.class.where(column_name => candidates).pluck(column_name) (candidates - already_used).first(count) end # Usage example: model = Domain.new model.name = 'hello-world' generate_alternative_names(model, :name, 5) # => ["hello_world", "hello-world2", "world_hello", ...] It generates 100 candidates, then checks the database for matches and removes them from the candidates list. Finally it returns the first count values extracted. This method is a best effort implementation, as it works for small sets of suggestions, that have few conflicts (in my case, 100 conflicts). Even if I increase this magic number (100), it does not scales indefinitely. Do you know a method to improve this, so it can scale for large number of conflicts and without using magic numbers? |
Rails: Storing object in variable within multi-tenant application Posted: 13 Apr 2016 05:55 AM PDT In my multi-tenant application I have model Config which is responsible for each tenant configuration stuff. It has no relation with the tenant, as it is already within the scope of Tenant.current . So I just call it as Config.first where needed (I use it in few controllers as well as in few models(as a scope argument)). The problem is that it hits DB each time it's called, but actually most of time it will be unchanged, so I would like to do something like def current_config @config ||= Config.first end but I can not imagine a place for it to be done this way, so I have it 1) stored within one exact tenant; 2) accessable app-wide. Please share Your suggestions |
Execute Javascript each time an external POST request is received Posted: 13 Apr 2016 06:05 AM PDT I have in my PagesController: def webhook_post respond_to do |format| format.js end end And a webhook_post.js.erb file in my views/pages folder. I have this route: post '/webhook', to: "pages#webhook_post" I would like to execute the webhook_post.js.erb file each time an external POST request (from another site) is sent to it. When trying from my terminal (Mac): curl -X POST http://localhost:3000/webhook The javascript appears in the console but isn't executed. I only have one line of JS to try it out but it still gets displayed and not executed. What I'd like to do: - receive the POST request with some data passed through the params - store this data in variables in my webhook_post action - pass this data to an AJAX call that will send it to another server as json So my question is: how can I execute a script after the POST request is received ? |
Session gets lost after redirect Posted: 13 Apr 2016 05:51 AM PDT When a user visits a index Im redirecting him to show . As you can see in index i'm setting a variable in setting skip_before_filter :verify_authenticity_token, only: :show def show debugger render inline: "<h3>hello</h3>" end def index session[:user] = "hans" debugger redirect_to action: "show" end When I use debugger in the action show : session => #<ActionDispatch::Request::Session:0x7f9a8e0882e0 not yet loaded> Then when I force to initialise the session with: session[:init] = true Then there is a session but session[:user] == nil and the session_id is also different form the session_id I get in index . What do I wrong? Why does it start a new session after the redirect? Thanks |
Rails - Serialize related data Posted: 13 Apr 2016 06:22 AM PDT I've got two models: class Continent < ActiveRecord::Base has_many :countries end class Country < ActiveRecord::Base belongs_to :continent end I created controller like: class ContinentsController < ApplicationController def index @continents = Continent.all render json: @continents end end and serializer: class ContitnentSerializer < ActiveModel::Serializer attributes :name, :countries end Here my issue begins. I'd like to serialize only countries with given condition where value comes from HTTP GET params. E.g country inside serializer should be displayed only if population is more than params[:population]. The problem is inside serializer we don't have access to params to examine that. [ { name: 'Europe' countries: [ { name: 'Italy', population: 1000000 } ] }, { name: 'Africa' countries: [ ] } ] I've tried to join table with condition but it seems be not working. @continents = Continent.all.joins("LEFT JOIN countries ON countries.continent_id = continents.id AND countries.population > #{params[:population]}") |
one month rails pinterest clone adding omniauth Facebook authentication Posted: 13 Apr 2016 05:36 AM PDT I have setup a pinterest website clone from onemonth.com tutorials. However, I found another tutorial on adding omniauth Facebook authentication to devise. I can login, but when i try to access the add pin function it produces an error. https://github.com/hcharrington/rememberch NoMethodError in PinsController#new undefined method `pins' for #<User:0x007fc3fc7e0ac8> Extracted source (around line #20): def new @pin = current_user.pins.build end |
NameError: undefined local variable or method `user' Posted: 13 Apr 2016 05:41 AM PDT I'm writing an app using RoR, using gem Devise for user authentication. I'm trying to test user behaviour when he signed in the app and have next error: User::TransactionsController when logged in when its own record GET #show assigns the requested instance as @instance Failure/Error: let(:transaction) { FactoryGirl.create(:transaction, user_id: user.id) } NameError: undefined local variable or method `user' for #<RSpec::ExampleGroups::UserTransactionsController::WhenLoggedIn::WhenItsOwnRecord::GETShow:0x00000004d77220> My tests start with: RSpec.describe User::TransactionsController, type: :controller do render_views before { sign_in FactoryGirl.create :user } let(:transaction_category) { FactoryGirl.create(:transaction_category) } let(:transaction) { FactoryGirl.create(:transaction, user_id: user.id) } ...... end My factory: FactoryGirl.define do factory :transaction do date '2016-01-08' comment 'MyString' amount 1 transaction_category trait :invalid do amount nil end end end My TransactionsController looks like: class User::TransactionsController < ApplicationController before_action :authenticate_user! before_action :find_transaction, only: [:show, :edit, :destroy, :update] def new @transaction = current_user.transactions.build end def show end def create @transaction = current_user.transactions.build(transaction_params) if @transaction.save redirect_to user_transaction_url(@transaction) else render :new end end def index @transactions = current_user.transactions end def edit end def destroy @transaction.destroy redirect_to user_transactions_url end def update if @transaction.update(transaction_params) redirect_to user_transaction_url else render :edit end end private def transaction_params params.require(:transaction).permit(:amount, :date, :comment, :transaction_category_id) end def find_transaction @transaction = current_user.transactions.find(params[:id]) end end Thanks! |
Devise - undefined local variable or method `current_member' Posted: 13 Apr 2016 05:49 AM PDT I am using members as the Devise model. I have placed before_action :authenticate_member! in the application controller. But when i try to use the following in the views <%= current_member.inspect %> Am getting the following error undefined local variable or method `current_member' for #<#<Class:0x007fe48ad32130>:0x007fe48e389af8> #<Class:0x007fe48ad32130>#_app_views_brands_members_index_html_erb___144793605481589474_70309807670200 app/views/brands/members/index.html.erb, line 1 <%= current_member.inspect %> <%= link_to('Logout', destroy_brands_member_session_path, :method => :delete) %> Member Model - app/model/member.rb class Member < ActiveRecord::Base # Include default devise modules. Others available are: # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable acts_as_paranoid # Associations belongs_to :company accepts_nested_attributes_for :company end Devise Initialiser config.default_scope = :member Controller class Brand::ApplicationController < ApplicationController before_action :authenticate_member! private end Members Controller brands/members_controller.rb class Brands::MembersController < Brand::ApplicationController def index end end ROUTEs Rails.application.routes.draw do # devise_for :members # Brands Routes constraints :subdomain => "brands" do scope :module => "brands", :as => "brands" do # namespace :brands do # devise_for :members devise_for :members, controllers: { sessions: 'brands/members/sessions', registrations: 'brands/members/registrations', confirmations: 'brands/members/confirmations', passwords: 'brands/members/passwords' } get '/members' => 'members#index' end end # API Routes constraints :subdomain => "api" do scope :module => "api", :as => "api" do api_version( module: "V1", header: { name: "Accept", value: "application/vnd.skreem+json; version=1" }, defaults: { format: :json } ) do # devise_for :members # resources :products end end end end |
Carrierwave upload to Amazon S3 from a rake task: can't get upload to work Posted: 13 Apr 2016 05:16 AM PDT I am trying to generate a csv file in a rake task and... - Email it
- Upload it to Amazon s3.
Here is the task. desc "This task is called by the Heroku scheduler add-on" require 'csv' task :send_report => :environment do file = Baseline.to_csv ReportMailer.database_report(file).deliver_now Report.create!(:data => file) end The generation of the csv file and attachment to the email works fine (not shown). Its the carrierwave upload that isn't working. Please note that I have other uploaders for other models and they work fine so my bucket settings are correct. Here are the other files. class Report < ActiveRecord::Base mount_uploader :data, ReportUploader end and class ReportUploader < CarrierWave::Uploader::Base storage :fog def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end def extension_white_list %w(jpg jpeg gif png csv xls) end end I have tried various permutations such as store! with not luck. I should add that if I look at the database, the new report is being created (and the data attribute is "nil", with no upload in sight) Thanks |
Rails date_select values always 0 Posted: 13 Apr 2016 05:23 AM PDT I've been trying for a while but I can't seem to access date_select values. The view looks like this: <%= form_for(@product) do |form| %> ... <%= form.label :release_date %> <%= date_select :@product, :release_date %> ... When the form is submitted I can see that the values are definitely there as the POST contains: Parameters: ... "product"=> { "@product"=>{"release_date(1i)"=>"2016", "release_date(2i)"=>"4", "release_date(3i)"=>"13"} ... } From the answer to a similar question; How to get a Date from date_select or select_date in Rails? it would seem that the correct code to get the value from the key "release_date(1i)" should be something like: product = params[:product] date = product["release_date(1i)"].to_i However the value for date is always 0. Any advice would be appreciated. |
Nested has_many in rails Posted: 13 Apr 2016 06:24 AM PDT I have separate classes Article, User and Image class Article < ActiveRecord::Base has_many :users end class User < ActiveRecord::Base has_many :images end class Image < ActiveRecord::Base end I would like to find all images from all users relating to a particular article. imgs = article.users.images Is there a way to recurse into the list of users to extract and concatenate all of the images? |
How to get column value with insert query using sequel? Posted: 13 Apr 2016 06:53 AM PDT How to fetch column value at the time of inserting into MySQL DB using sequel. Tried below query getting type error: no implicit conversion to integer. DB[:table].import([:x, :y], [[1, 2]], [:return=>:primary_key]). |
There was an error while trying to load the gem 'rails-api'. (Bundler::GemRequireError) Posted: 13 Apr 2016 05:22 AM PDT I am working with Rails 5.0.0.beta3 and creating a rails-api. when i run rails-api generate scaffold user email:string password:string auth_token:string it shows the error .rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in `rescue in block (2 levels) in require': There was an error while trying to load the gem 'rails-api'. (Bundler::GemRequireError) from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in `block (2 levels) in require' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `each' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in `block in require' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `each' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in `require' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/bundler-1.11.2/lib/bundler.rb:99:in `require' from /home/ahsanul/Documents/rails-api/my_blog/config/application.rb:7:in `<top (required)>' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/spring-1.7.1/lib/spring/application.rb:82:in `require' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/spring-1.7.1/lib/spring/application.rb:82:in `preload' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/spring-1.7.1/lib/spring/application.rb:143:in `serve' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/spring-1.7.1/lib/spring/application.rb:131:in `block in run' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/spring-1.7.1/lib/spring/application.rb:125:in `loop' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/spring-1.7.1/lib/spring/application.rb:125:in `run' from /home/ahsanul/.rvm/gems/ruby-2.2.3/gems/spring-1.7.1/lib/spring/application/boot.rb:19:in `<top (required)>' from /home/ahsanul/.rvm/rubies/ruby-2.2.3/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require' from /home/ahsanul/.rvm/rubies/ruby-2.2.3/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54:in `require' from -e:1:in `<main>' How can i resolve the problem? |
Rails AWS Delete file from S3 Posted: 13 Apr 2016 05:00 AM PDT I've been trying all morning to get this to work, from pulling parts of other pages on stack and my own ideas but i seem to be failing. I'm trying to connect to my bucket on s3 and do 1 of 2 things, I don't mind which one, once it works. I need to either delete the file after an update or else copy it with a new name and then delete the original. I'll paste my code here along with the commented out bits so you can see what I've been trying. The update part of my file is working fine but at the moment the closest i've gotten to getting it to work is as far as the aws part near the bottom, I'm now getting an error NoMethodError: undefined method `bucket' for :AWS::S3 I think I might be mixing up s3 or aws, or the versions of the aws, not too sure, any help would be great. Thanks require 'open-uri' require 'csv' desc "Imports a CSV file into an ActiveRecord table" task :update, [:filename] => :environment do CSV.new(open("https://s3-eu-west-1.amazonaws.com/recharge-cartridges/recharge_pricing.csv"), :headers => true).each do |row| product = Spree::Product.find_or_create_by(ts_code: row["ts_code"]) parameters = ActionController::Parameters.new(row.to_hash) product.update(parameters.permit(:cost_price,:price)) end print "--- setting up Amazon s3 connection ---" #amazon = AWS::S3::Client.new(access_key_id:ENV["AWS_ACCESS_KEY_ID"] , secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"]) #bucket = amazon.buckets.find("recharge-cartridges") #print "--- Service started and bucket found ---" #print "--- Starting to copy file and delete original ---" s3 = AWS::S3.new(access_key_id:ENV["AWS_ACCESS_KEY_ID"] , secret_access_key: ENV["AWS_SECRET_ACCESS_KEY"]) s3.bucket('recharge-cartridges').delete_key('recharge_pricing.csv') #amazon.move_to(bucket: "recharge-cartridges", #copy_source: URI::encode("recharge-cartridges/recharge_pricing.csv"), #key: "import_rename.csv") #amazon.delete_object(bucket: "recharge-cartridges", #key: "recharge_pricing.csv") end |
ROR + Savon along with SOAP Posted: 13 Apr 2016 04:59 AM PDT I am trying with Savon gem to consume WSDL. Here is the WSDL sample. Sample code in IRB >> client = Savon .client(wsdl: "http://www.webservicex.com") This is not the real address. just test url >> client.operations it returns the [:rate_quote, :rate_quote_xml] <?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/ClientServices/ClientServices"> <SOAP-ENV:Body> <ns1:RateQuote> <ns1:ClientCode>"xxx"</ns1:ClientCode> <ns1:UserName>"xxx"</ns1:UserName> <ns1:OriginZip>"02347"</ns1:OriginZip> <ns1:DestinationZip>"30336"</ns1:DestinationZip> <ns1:ShipmentDate>2016-04-13T13:45:30.0900000</ns1:ShipmentDate> <ns1:Items> <ns1:Item> <ns1:ItemClass>"55"</ns1:ItemClass> <ns1:Weight>115</ns1:Weight> <ns1:Length>15</ns1:Length> <ns1:Width>25</ns1:Width> <ns1:Height>20</ns1:Height> </ns1:Item> </ns1:Items> <ns1:Accessorials> <ns1:Accessorials> <ns1:ServiceCode>"CBC"</ns1:ServiceCode> <ns1:Service>?</ns1:Service> </ns1:Accessorials> </ns1:Accessorials> </ns1:RateQuote> </SOAP-ENV:Body> </SOAP-ENV:Envelope> I would like to pass these parameters through ruby code to get the response. Could someone help me how to do this? |
Run one particular controller action through the cron in rails Posted: 13 Apr 2016 05:40 AM PDT I have to run one particular controller action through the cron in rails. My code for this is: every 1.minutes do runner "Count.get_value", output: { error: "#{path}/log/error.log", standard: "#{path}/log/cron.log" } end Above code works fine with model action, but I need to run controller action through the cron. Can someone help me? |
Thank you for providing useful contentRuby on Rails Online Course India
ReplyDelete