Add Custom fields with paypal recurring Posted: 16 May 2016 06:56 AM PDT i have integrated paypal recurring on my site and i have integrated instant payment notifications for recurring success and failure, everything works perfect except the user email. i want to send the user email of my site with the parameters, so that i can send email to them whenever there is some change in recurring payment. I have tried to send the parameter with the request but when i get the ipn response i get empty custom parameter. result = paypal_obj = PayPal::Recurring.new({ :amount => pkg_amount, :currency => "USD", :description => "#{params[:description]}" , :ipn_url => "/subscriptions/paypal_response", :frequency => 1, :token => "#{params[:token]}", :period => "#{@package.rebill_type}", :reference => "1234", :payer_id => "#{params[:PayerID]}", :start_at => start_time , :failed => 1, :custom => 'teest@live.com' :initial_amount => @your_total_amount_in_cents, :outstanding => :next_billing }) How do i send the custom field, because the above one does not work for me. |
Error in submittion of signup form Posted: 16 May 2016 06:52 AM PDT When testing for submittion of signup form I keep getting the errors Failure/Error: @user = User.new(params[:user]) ActiveModel::ForbiddenAttrubutesError:
Error Image users_controller.rb class UsersController < ApplicationController def show @user = User.find(params[:id]) end def new @user = User.new end def create @user = User.new(params[:user]) if @user.save redirect_to @user else render 'new' end end private def user_params params.require(:user) .permit(:name, :email, :password, :password_confirmation) end end schema.rb ActiveRecord::Schema.define(version: 20160510092655) do create_table "users", force: :cascade do |t| t.string "name" t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "password_digest" end add_index "users", ["email"], name: "index_users_on_email", unique: true end user_pages_spec.rb require 'rails_helper' RSpec.describe "UserPages", type: :request do subject {page} describe "profile page" do let (:user) { FactoryGirl.create(:user)} before { visit user_path(user)} it { should have_selector('h1', text: user.name) } it { should has_selector?('title', text: user.name) } end describe "signup page" do before {visit signup_path} it {should has_selector?('h1', text: 'Signup')} it {should has_selector?('title', text: full_title('Sign Up'))} end describe "singup" do before { visit signup_path } let(:submit) { "Create my account" } describe "with invalid information" do it "should not create a user" do expect { click_button submit }.not_to change(User, :count) end end describe "with valid information" do before do fill_in "Name", with: "Example User" fill_in "Email", with: "user@example.com" fill_in "Password", with: "foobar" fill_in "Confirmation", with: "foobar" end it "should create a user" do expect { click_button submit }.to change(User, :count).by(1) end end end end |
ActiveRecord + Pry confusion Posted: 16 May 2016 06:33 AM PDT This is confusing me no end. In a rake task, I am saving new records on the DailyScore model with the following code: def save_record_as_daily_score_object(data) @ds = DailyScore.where(date: data[:date]).first_or_create! @ds.update!(data) binding.pry end The pry output is as follows: [10] pry(main)> data => {:date=>"2015-09-02", :mail=>-0.6, :times=>-7.1, :telegraph=>-2.2, :guardian=>-4.0, :express=>-0.1, :independent=>-3.2, :average=>-3.4} [11] pry(main)> @ds => #<DailyScore:0x000001098121a8 id: 4975, mail: nil, telegraph: nil, times: nil, average: nil, guardian: nil, independent: nil, express: nil, date: nil, created_at: 2016-05-16 13:10:03 UTC, updated_at: 2016-05-16 13:10:03 UTC> [12] pry(main)> @ds.average => -3.4 [13] pry(main)> @ds.date => "2015-09-02" [14] pry(main)> @ds.persisted? => true [15] pry(main)> DailyScore.last => #<DailyScore:0x000001086810d8 id: 4975, mail: nil, telegraph: nil, times: nil, average: nil, guardian: nil, independent: nil, express: nil, date: nil, created_at: 2016-05-16 13:10:03 UTC, updated_at: 2016-05-16 13:10:03 UTC> [16] pry(main)> DailyScore.last.average => nil What is going on here? Why can't Pry access my variable attributes? And is the record actually being saved or not? |
Can I create a local blockchain with Ruby on Rails or Node.js instead of Ethereum? Posted: 16 May 2016 06:31 AM PDT I have to craft an internship project for this summer and it has to be on blockchain. I have been looking at Ethereum, which seems pretty good. The GETH command line interface seems to allow me to be able to create a local blockchain and then allow me to mine that blockchain. However, I really would like to be able to use Ruby on Rails , Node.js, or another web framework so I could have the interns create a UI to go along with the blockchain. I have looked at Toshi(RoR) and BitCoin.js(Node), but neither of them seem to have a lot of documentation. Does anyone know a good framework to create blockchain applications, from server to miners? It does not have to be in Node.js or Ruby on Rails, those were just the two technologies that I am most familiar with. Thanks for any and all your help! |
Ruby on Rails website errors after VPS upgrade Posted: 16 May 2016 06:40 AM PDT Our VPS was just upgraded from Debian Squeeze and php 5.2 to Ubuntu and php 5.5, our website (coded in Ruby) is now down with all sorts of fun errors: our URL: http://grfxpstore.com/ Here's a link to what has changed: http://wiki.dreamhost.com/EOL_Debian_4.0,_5.0,_and_6.0_on_VPS#Overview Unfortunately I'm not at all a web admin (actually a dba), and our former webmaster is not available for questioning! Any help or assistance as to what is going on, if there are possible fixes (or not) would be greatly appreciated! This is the error with backtrace: undefined method `name' for "BlueCloth":String (NoMethodError) /home/grfxp_edge/rails/grfxp_web/releases/20130606051836/config/../vendor/rails/railties/lib/rails/gem_dependency.rb:277:in `==' /usr/lib/ruby/vendor_ruby/1.8/rubygems/dependency.rb:217:in `===' /usr/lib/ruby/vendor_ruby/1.8/rubygems/dependency.rb:217:in `matching_specs' /usr/lib/ruby/vendor_ruby/1.8/rubygems/custom_require.rb:36:in `find_all' /usr/lib/ruby/vendor_ruby/1.8/rubygems/specification.rb:410:in `each' /usr/lib/ruby/vendor_ruby/1.8/rubygems/specification.rb:409:in `each' /usr/lib/ruby/vendor_ruby/1.8/rubygems/dependency.rb:216:in `find_all' /usr/lib/ruby/vendor_ruby/1.8/rubygems/dependency.rb:216:in `matching_specs' /usr/lib/ruby/vendor_ruby/1.8/rubygems/dependency.rb:238:in `to_specs' /usr/lib/ruby/vendor_ruby/1.8/rubygems/dependency.rb:256:in `to_spec' /usr/lib/ruby/vendor_ruby/1.8/rubygems.rb:1208:in `gem' /home/grfxp_edge/rails/grfxp_web/releases/20130606051836/config/../vendor/rails/railties/lib/rails/gem_dependency.rb:75:in `add_load_paths' /home/grfxp_edge/rails/grfxp_web/releases/20130606051836/config/../vendor/rails/railties/lib/initializer.rb:301:in `add_gem_load_paths' /home/grfxp_edge/rails/grfxp_web/releases/20130606051836/config/../vendor/rails/railties/lib/initializer.rb:301:in `each' /home/grfxp_edge/rails/grfxp_web/releases/20130606051836/config/../vendor/rails/railties/lib/initializer.rb:301:in `add_gem_load_paths' /home/grfxp_edge/rails/grfxp_web/releases/20130606051836/config/../vendor/rails/railties/lib/initializer.rb:132:in `process' /home/grfxp_edge/rails/grfxp_web/releases/20130606051836/config/../vendor/rails/railties/lib/initializer.rb:113:in `send' /home/grfxp_edge/rails/grfxp_web/releases/20130606051836/config/../vendor/rails/railties/lib/initializer.rb:113:in `run' /home/grfxp_edge/rails/grfxp_web/releases/20130606051836/config/environment.rb:21 /usr/lib/ruby/vendor_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require' /usr/lib/ruby/vendor_ruby/1.8/rubygems/custom_require.rb:36:in `require' /dh/passenger/helper-scripts/classic-rails-preloader.rb:96:in `preload_app' /dh/passenger/helper-scripts/classic-rails-preloader.rb:184 |
Rails cross domain ajax request Posted: 16 May 2016 06:27 AM PDT I'm trying to implement google places api in my rails app for finding restaurants near my location. This is the error I'm getting when trying to use the function that is fetching the data from the ajax request: XMLHttpRequest cannot load . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. I'm using rack-cors gem and I've added this snippet into my config/application.rb file: config.middleware.insert_before 0, "Rack::Cors" do allow do origins '*' resource '*', :headers => :any, :methods => [:get, :post, :options] end end This is the ajax request from my view (coffeescript): $.ajax url: url dataType: "json" crossDomain: true type: "GET" and I've noticed that my request headers remain unchanged. (Access-Control-Allow-Origin is not added to request headers) Request URL: (not relevant) Request Method:OPTIONS Status Code:200 Remote Address: (not relevant) Response Headers alt-svc:quic=":443"; ma=2592000; v="33,32,31,30,29,28,27,26,25" alternate-protocol:443:quic cache-control:public, max-age=300 content-encoding:gzip content-length:538 content-type:application/json; charset=UTF-8 date:Mon, 16 May 2016 12:59:48 GMT expires:Mon, 16 May 2016 13:04:48 GMT server:pablo status:200 vary:Accept-Language x-frame-options:SAMEORIGIN x-xss-protection:1; mode=block Request Headers Provisional headers are shown Access-Control-Request-Headers:accept, x-csrf-token Access-Control-Request-Method:GET Origin:http://localhost:3000 Referer:http://localhost:3000/restil/new? User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36 Query String Parameters view source view URL encoded location:( not relevant) radius:5000 type:restraunt key: (not relevant) jsonp is not an option because it's not supported by places api |
Make a class filterable on a delegated attribute Posted: 16 May 2016 06:32 AM PDT I have an application in RoR4 that has the following model: # Quotation model class Quotation < ActiveRecord::Base belongs_to :request has_one :booking has_one :review has_one :coupon, class_name: 'Coupons::Models::CouponRedemption' delegate :artist, to: :request delegate :user, to: :request end I am trying to make a query that can find show all Quotation objects that are linked with a certain user. I tried to do it with the following: # Scope to filter based on user scope :_user, -> (user_id) { where user: user_id } This however returns "undefined method `user'", do you know what I am doing wrong? |
before destroy call back Posted: 16 May 2016 06:34 AM PDT I am a novice Ruby programmer working on a Rails API. I have a Location model and a User model, and a location has many users. They are related like this: class Location << ActiveRecord::Base has_many: :users end class User << ActiveRecord::Base belongs_to :location end I want to put a constraint on the Location model so that a Location model object won't be destroyed if it has one or more associated Users. Consider the case of Mumbai, which is a Location and it has one or more Users. As such, I cannot destroy that Location; I can destroy only if there are no users for a particular location. How do to handle destroying records in a protected manner, such as this? |
Usage of html_safe attribute in Prawn PDF syntax Posted: 16 May 2016 06:13 AM PDT I'm rendering the PDF data from the output of CK editor (What you see is what you get editor). The output from that editor would be included with all the HTML, CSS tags in the content. For that I had used 'html_safe' attribute in the show page. But when I try to use the same attribute in the PDF prawn syntax its not working. Can someone please guide me how to get the pure content without all the HTML tags in Prawn PDF. Thanks in advance. |
Not able to connect with PostgreSQL database with Rails app Posted: 16 May 2016 06:12 AM PDT I am having an issue while trying to connect with a PG database in my Rails application: I've create my new app with the following command: $ rails new -d postgresql myApp
The application was created successfully. Therefore I proceed with the following command: $ createuser --createdb --login -P myApp The prompt asks me a password for a new role. I enter the password and re-enter it for confirmation. This the message I get after entering the password: createuser: could not connect to database postgres: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
Any help? I am using PG version 9.5.3 and Ruby on Rails version 4.2.4 |
How to reuse one association in another in rails 4.2.1 Posted: 16 May 2016 06:57 AM PDT I have a model User . I have the following associations: has_many :user_schools has_many :schools, through: :user_schools, source: :school has_many :active_schools, -> {where(active: true)}, through: :user_schools, source: :school How can I reuse :schools to write the association for :active_schools without repeating the following: through: :user_schools, source: :school` |
rails+rspec controller spec with polymorphic association Posted: 16 May 2016 06:00 AM PDT I'm trying to test the actions in controller spec but for some reason I get the no routes matches error. What should I do to make the route work? ActionController::UrlGenerationError: No route matches {:action=>"create", :comment=>{:body=>"Consectetur quo accusamus ea.", :commentable=>"4"}, :controller=>"comments", :post_id=>"4"} model class Comment < ActiveRecord::Base belongs_to :commentable, polymorphic: true, touch: true class Post < ActiveRecord::Base has_many :comments, as: :commentable, dependent: :destroy routes resources :posts do resources :comments, only: [:create, :update, :destroy], module: :posts end controller_spec describe "POST create" do let!(:user) { create(:user) } let!(:profile) { create(:profile, user: @user) } let!(:commentable) { create(:post, user: @user) } context "with valid attributes" do subject(:create_action) { xhr :post, :create, post_id: commentable, comment: attributes_for(:comment, commentable: commentable, user: @user) } it "saves the new task in the db" do expect{ create_action }.to change{ Comment.count }.by(1) end ... |
Have to integrate rails devise :lockable functionality with ember-simple-auth Posted: 16 May 2016 05:58 AM PDT I want to implement the user lockable functionality for an app which uses Ember-cli as a front-end and Rails using grape-api as a back-end. I used ember-simple-auth and devise gem for user management. The problem is, the user model on the rails side does not get updated for the invalid login attempts and the devise lockable is not working. The login functionality is working properly. Rails: 4.2.5, Ember-cli: 2.4.5, Ember-simple-auth: 1.1.0-beta.5 Ember: login.js import Ember from 'ember'; const { service } = Ember.inject; export default Ember.Component.extend({ session: service('session'), actions: { authenticate() { let { identification, password } = this.getProperties('identification', 'password'); return this.get('session').authenticate('authenticator:devise', identification, password).catch((reason) => { this.set('errorMessage',reason.error); console.log(reason.error.message); }); } } }); Rails: model/user.rb ... devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :confirmable, :lockable ... db/migration.rb Have include Lockable attributes in devise user migration ... ## Lockable t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts t.string :unlock_token # Only if unlock strategy is :email or :both t.datetime :locked_at ... config/initializers/devise.rb ==> Configuration for :lockable ... config.lock_strategy = :failed_attempts config.unlock_strategy = :email config.maximum_attempts = 3 config.last_attempt_warning = true ... user_api.rb ... post "sign_in" do email = params[:user][:email] password = params[:user][:password] user = User.find_by(email: email.downcase) if !user.valid_password?(password) error!({ error: { status_code: 401, message: "Invalid password"}},401) return else user.ensure_authentication_token user.save {token: user.authentication_token, email: user.email, name: user.name} end end ... |
React.js on Rails Order Array Posted: 16 May 2016 06:24 AM PDT how i can show my array in order ASC or DESC an example. here is my react component var News = React.createClass({ displayName: 'News', render: function() { return ( <div> <div> <h4>{this.props.news.title}</h4></div> <div>{this.props.news.created_at}</div> <div>{this.props.news.body}</div> </div> ); } }); and here is my render <% @news.each do |news| %> <%= react_component('News', { :news => news }) %> <% end %> |
Postgresql duplicate primary key Posted: 16 May 2016 04:53 AM PDT I am woking on PG 9.2.14 on our production server I am facing some random issue. Let's say its a table named users and id is the primary key in it. When I am trying to reindex the table it give me following error:- ERROR: could not create unique index "users_pkey" DETAIL: Key (id)=(339) is duplicated. When I am trying to fetch user with the 339 id, there is no record. I am not sure if its PG's bug or I am doing something wrong. Any one have faced such kind of problem? |
Redirect a http post request with modified http header to another server Posted: 16 May 2016 06:21 AM PDT I'm using Ruby on Rails. Here is the requirement: the client (a native mobile app developed by us) will send a http post request to my Ruby code, my code will add some extra http headers (based on some business logic), then I need to "forward" or "redirect" this post request to one of our backend servers and return its response back to the client. I have been able to write a rack middleware to intercept the post request and add the extra headers. Originally I thought I can just use http redirect (status code: 307 for post request). But the problem is that the extra headers could NOT be submitted, which is the whole point of my code. So this isn't http redirect or forwarding per se, it's more like transforming a request. I'm able to make a separate post request from my code using net http. This works. But I have to COPY data from the incoming request to my outgoing request (eg form data, http headers). This copying seems a bit tedious. I would prefer some kind of simple "repackaging" (which is akin to http redirect or forwarding), that is I copy the whole incoming request to the outgoing request, slap on the extra headers and send it to the destination URL and be done with. I am not sure how to do this, and if doing it this way is even a good idea. For example, HTTP_USER_AGENT shows the OS, browser type of the client, when I'm making a new request, I probably don't need to send this on. Alternatively, I can copy only the application specific data, because they're all the backend server (the destination of this "redirect") cares about. But I'm averse to hardcoding attributes in my code, causing close-coupling with the client (our native mobile app). Ideally I only copy application-specific data without hardcoding their attribute names. Is this possible? If so, how? Any advice would be appreciated. Thank you. |
Ruby on Rails Nested Form Posted: 16 May 2016 06:04 AM PDT I have three Models: Deal, Zipcode, DealIncludeZipcode. Now, the association looks like below:- Deal Model: class Deal < ActiveRecord::Base has_many :deal_include_zipcodes, dependent: :destroy has_and_belongs_to_many :zipcodes, dependent: :destroy accepts_nested_attributes_for :deal_include_zipcodes,:reject_if => :reject_include_zipcodes, allow_destroy: true private def reject_include_zipcodes(attributes) if attributes[:deal_id].blank? || attributes[:zipcode_id].blank? if attributes[:id].present? attributes.merge!({:_destroy => 1}) && false else true end end end end class Zipcode < ActiveRecord::Base has_and_belongs_to_many :deals end class DealIncludeZipcode < ActiveRecord::Base belongs_to :deal belongs_to :zipcode end Now in view I have a checkbox,on unchecking it I can select multiple zipcode to select from DealIncludeZipcode.But when I save the data it is not saving. I have used migration for joining Zipcode and Deal Model in which my exclude zipcode functionality is working correctly. Please provide a soloution.I have tried various method but didn't got succeed. |
Proper use of Figaro with Heroku (keys upcase/downcase appear twice) Posted: 16 May 2016 04:53 AM PDT I'm using Heroku, and when I display the config vars: === someapp-staging Config Vars DATABASE_URL: xxx LANG: en_US.UTF-8 NEW_RELIC_LICENSE_KEY: xxx NEW_RELIC_LOG: stdout RACK_ENV: staging RAILS_ENV: staging SENDGRID_PASSWORD: 123456 SENDGRID_USERNAME: app123456@heroku.com WEBSOLR_URL: https://index.websolr.com/solr/0e1122334455 sendgrid_password: 654321 sendgrid_username: app654321@heroku.com websolr_url: https://index.websolr.com/solr/0e1122334455 ... some are defined more than once. Heroku' advice is to set all vars with uppercased keys. From https://devcenter.heroku.com/articles/add-ons: Alias names must always conform to the same naming conventions as config vars.They must begin with a letter and can only contain uppercase alphanumeric characters or underscores. 1 So... when we execute figaro heroku:set --remote staging -e staging for example, why Figaro doesn't automatically set the keys to uppercase? 2 What to do next? Must I set the vars in application.yml with mixed keys like: staging: <<: *default app_name: 'someapp (staging)' SENDGRID_USERNAME: app123456@heroku.com SENDGRID_PASSWORD: 123456 WEBSOLR_URL: 'https://index.websolr.com/solr/0e1122334455' geocoder_api_key: 'azertyuiop123456789' airbrake_project_id: "987654" airbrake_project_key: 'a123456z789456123' Thank you ps: those are not my real credentials. |
Routing Error uninitialized constant FavoriteSongsController Posted: 16 May 2016 04:41 AM PDT i have Rails 4.2.6 and ruby 2.3 , Following a tutorial for adding favorites to my existing project, whereby users can favorite property listings but can't get past the error below: Routing Error uninitialized constant FavoriteSongsController favorite_songs_Controller.rb class FavoriteSongsController < ApplicationController before_action :set_song def create if Favorite.create(favorited: @fav_song, user: current_user) flash[:success] = t('favorite_song.success') redirect_to :back else flash[:danger] = t('favorite_song.wrong') redirect_to :back end end def destroy Favorite.where(favorited_id: @fav_song.id, user_id: current_user.id).first.destroy flash[:info] = t('favorite_song.destroy') redirect_to :back end private def set_song @fav_song = Song.find(params[:song_id] || params[:id]) end end songs_controller.rb class SongsController < ApplicationController def show @artist = Artist.friendly.find(params[:artist_id]) @song = @artist.songs.find(params[:id]) end end song.rb class Song < ActiveRecord::Base include PgSearch belongs_to :artist default_scope -> { order(:title) } validates :artist_id, presence: true validates :title, presence: true, length: { maximum: 140 } has_attached_file :mp3, :url => "/songs/:artist_slug/:song_slug_:hash.:extension" validates_attachment :mp3, :content_type => { :content_type => ["audio/mpeg", "audio/mp3"] }, :file_name => { :matches => [/mp3\Z/] } validates_attachment_presence :mp3 validates_attachment_size :mp3, { less_than: 15.megabytes } Paperclip.interpolates :artist_slug do |attachment, style| attachment.instance.artist.slug end Paperclip.interpolates :song_slug do |attachment, style| attachment.instance.slug end Paperclip::Attachment.default_options.update({ :hash_secret => "jHLi3fdrmHZQ8r9wxGZbyyGzc9BT8UAxOk2q6O1T1ut+pgmDqmtFIdaBuw8tkhAK0nhDMrCQYCMfOXiUH3R27zG22OHi0852jK93/TaiDtymwzPXZQOxhM6KR6aODhEK+LmqYG1uIGHvqfzD1BOh/R7JuvW2cf+0dT0V3hiFEzA=" }) pg_search_scope :search_by_title, :against => :title, :using => { :trigram => { :threshold => 0.1 } } def slug=(value) if value.present? write_attribute(:slug, value) end end end user.rb class User < ActiveRecord::Base authenticates_with_sorcery! has_many :favorites has_many :favorite_songs, through: :favorites, source: :favorited, source_type: 'Song' validates :email, presence: true, length: { maximum: 255 }, email_format: { message: I18n.t('signup.email_invalid') }, uniqueness: { case_sensitive: false } validates :password, presence: true, confirmation: true, length: { minimum: 6} end favorite.rb class Favorite < ActiveRecord::Base belongs_to :favorited, polymorphic: true belongs_to :user end routes.rb Rails.application.routes.draw do mount RailsAdmin::Engine => '/admin', as: 'rails_admin' root 'home#index' get 'search', to: 'search#search' resources :users, only: [:index, :show, :edit, :update] get '/signup', to: 'users#new' post '/signup', to: 'users#create' get '/login', to: 'sessions#new' post '/login', to: 'sessions#create' get '/logout', to: 'sessions#destroy' resources :reset_passwords, only: [:new, :create, :update, :edit] resources :artists, :path => "/", only: [:show] do resources :songs, :path => "/", only: [:show] end resources :favorite_songs, only: [:create, :destroy] end songs/songs.html.erb <%= render 'favorite_songs/fav' %> favorite_songs/_fav.html.erb <% if logged_in? %> <%- unless current_user.favorites.exists?(id: @song.id) -%> <%= link_to 'Add to favorites', favorite_songs_path(song_id: @song), method: :post %> <%- else -%> <%= link_to 'Remove from favorites', favorite_song_path(@song), method: :delete %> <%- end -%> <% end %> I've watched various tututorials and followed numerous suggestions but dont seem to be able to solve the issue by myself. |
form_for generating bad path rails 4 Posted: 16 May 2016 04:19 AM PDT I have form for creating end editing Exhibit. I don't know why it didn't work, and redirect to GET exhibits/new not to the POST. Creating new exhibit work by the console so my controller works good. Here is log from server: Started GET "/exhibits/new" for 127.0.0.1 at 2016-05-16 13:07:47 +0200 Processing by ExhibitsController#new as HTML Type Load (0.3ms) SELECT "types".* FROM "types" Rendered exhibits/new.html.erb within layouts/application (3.8ms) User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]] Rendered layouts/_header.html.erb (1.8ms) Completed 200 OK in 100ms (Views: 98.4ms | ActiveRecord: 0.4ms) Started GET "/exhibits/new?utf8=%E2%9C%93&authenticity_token=RDfe%2Fp4OJ2LdrINbmtUqZvdLfprzK0jAkcmpJ42Ga1IFj2FP8tcUy9OniCqVCCDktbOtzG7Q4dV0%2BFLJiHNVYA%3D%3D&exhibit%5Btitle%5D=TEST&exhibit%5Bauthor%5D=TEST&exhibit%5Bdate_of_origin%5D=1234&exhibit%5Bdescription%5D=TEST&exhibit%5Bextra%5D=TEST&exhibit%5Bavatar%5D=&exhibit%5Btype_id%5D=Rze%C5%BAba&exhibit%5Bex_id%5D=5&commit=Zapisz" for 127.0.0.1 at 2016-05-16 13:08:04 +0200 Processing by ExhibitsController#new as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"RDfe/p4OJ2LdrINbmtUqZvdLfprzK0jAkcmpJ42Ga1IFj2FP8tcUy9OniCqVCCDktbOtzG7Q4dV0+FLJiHNVYA==", "exhibit"=>{"title"=>"TEST", "author"=>"TEST", "date_of_origin"=>"1234", "description"=>"TEST", "extra"=>"TEST", "avatar"=>"", "type_id"=>"Rzeźba", "ex_id"=>"5"}, "commit"=>"Zapisz"} Type Load (0.3ms) SELECT "types".* FROM "types" Rendered exhibits/new.html.erb within layouts/application (4.4ms) User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]] Rendered layouts/_header.html.erb (1.5ms) Completed 200 OK in 71ms (Views: 69.8ms | ActiveRecord: 0.4ms) My form: <div class="col-xs-4"> <form> <%= form_for @exhibit do |f| %> <% if @exhibit.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@exhibit.errors.count, "error") %> prohibited this exhibit from being saved:</h2> <ul> <% @exhibit.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="form-group"> <label>Nazwa eksponatu: </label><br> <%= f.text_field :title, :class=>"form-control" %> </div> <div class="form-group"> <label>Autor: </label> <%= f.text_field :author, :class=>"form-control" %> </div> <div class="form-group"> <label>Data powstania: </label> <%= f.number_field :date_of_origin, :class=>"form-control" %> </div> <div class="form-group"> <label>Opis: </label> <%= f.text_field :description, :class=>"form-control text" %> </div> <div class="form-group"> <label>Ciekawostka: </label> <%= f.text_field :extra, :class=>"form-control" %> </div> <div class="text-center"> <label>Zdjęcie: </label> <%= f.file_field :avatar, :class=>"file", :id=> "file" %> </div> <div class="form-group"> <label>Typ eksponatu: </label> <%= f.select :type_id, options_for_select(@types.map { |type| [type.name]} )%> </div> <div class="form-group"> <label>Numer eksponatu: </label> <%= f.number_field :ex_id %> </div> </br> <div class="actions"> <%= f.submit 'Zapisz', :class=> 'btn btn-primary' %> </div> <% end %> </form> </div> here is my controller: https://github.com/schadock/museum-app/blob/master/app/controllers/exhibits_controller.rb |
Order and Limit for the Includes Table - Direction "{:processed_on=>:desc}" is invalid Posted: 16 May 2016 04:14 AM PDT I have the followings users has_many metrics I want to find all the users with 1 row of the metrics with order('processed_on desc') and limit(1) What i am trying User.includes(:metrics).where(status: 'active').order(:metrics => { processed_on: :desc }).limit(1) Error: Direction "{:processed_on=>:desc}" is invalid. Valid directions are: [:asc, :desc, :ASC, :DESC, "asc", "desc", "ASC", "DESC"] |
Rails form not causing errors Posted: 16 May 2016 05:35 AM PDT I've been working on a rails form and think I've messed something up, but cant put my finger on what. To give an overview. I have created a 1 page site with a contact form at the bottom. I have looked around for similar questions and they seem to have the contact form on another page with another controller, so can't find an answer for me. I know I've missed something, but can't figure out what. I get an error which states First argument in form cannot contain nil or be empty My main_controller.rb is as follows class MainController < ApplicationController def new @contact = Contact.new end def create @contact = Contact.new(contact_params) @contact.request = request if @contact.deliver redirect_to thank_you_path else flash.now[:error] = 'Cannot send message.' render :index end end private def contact_params params.require(:contact).permit(:name, :email, :phone, :message) end end contact.rb is class Contact < MailForm::Base attribute :name, :validate => true attribute :email, :validate => /\A([\w\.%\+\-]+)@([\w\-]+\.)+([\w]{2,})\z/i attribute :phone, :validate => true attribute :message, :validate => true def headers { subject: "Quote Form", to: "email-addy@gmail.com", from: %("#{name}" <#{email}>) } end end index.html.erb <%= bootstrap_form_for(@contact, layout: :horizontal, label_col: "col-sm-2", control_col: "col-sm-10") do |f| %> form template here <% end %> routes/rb Rails.application.routes.draw do resources :main, only: [:new, :create] root 'main#index' get '/thank-you' => 'main#thank-you' end |
Selected values radio_button rails Posted: 16 May 2016 04:11 AM PDT How to get the value of the selected element. And save it in a variable for display in span. I tried to save directly to the database. The database also does not save the selected value. ... <%= f.collection_radio_buttons( :route_id, Route.all, :id, :time_trip, {}, {name: "timeselect", class: "timeselect"}) %> ... <span id="timevalue"></span> Jquery (document).ready(function () { $('input[name="timeselect"]:radio').change(function(){ var str3=""; $('input[name="timeselect"]:checked').val(); str3 += $(this).text() + "\n"; $("#timevalue").text(); }); }); |
call the self object inside update_all in rails Posted: 16 May 2016 03:39 AM PDT I have a situation like, I have a product table which has a JSON field, I have to call a method to update that. So there are two approaches Product.all.each do |pr| pr.update_column(:boolean_tree, pr.change_boolean_tree) end There is nothing wrong with this apart from performance . To improve the performance we can run raw SQL . Which will definitely works fine, but not in a rails way. I was thinking is it possible to use update_all for this kind of situation. Any idea ? |
User session gets expired after returning from third party payment site. How to keep the user session alive? Posted: 16 May 2016 03:24 AM PDT In my rails app, I have a http cart page. Users get redirected to a third party payment site (I am using payumoney) for payment, which is https. After successfull payment when I try to load the 'your orders' page for the current user, I am getting current_user as nil. There is a success url field in payumoney inegration, the current value of which is "http://example.com/orders". How do I fix this? |
How skip user confirmation with email for omniauth(social authentication) Posted: 16 May 2016 05:22 AM PDT My omniauth_callbacks_controller.rb class OmniauthCallbacksController < Devise::OmniauthCallbacksController def facebook @user = User.from_omniauth(request.env["omniauth.auth"]) if @user.persisted? sign_in_and_redirect @user, :event => :authentication set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format? else session["devise.facebook_data"] = request.env["omniauth.auth"] redirect_to new_user_registration_url end end def google_oauth2 @user = User.from_omniauth(request.env['omniauth.auth']) if @user.persisted? sign_in_and_redirect @user, :event => :authentication set_flash_message(:notice, :success, :kind => "Google") if is_navigational_format? else session["devise.google_oauth2_data"] = request.env["omniauth.auth"] redirect_to new_user_registration_url end end end My usermodel is, def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.fullname = auth.info.name user.provider = auth.provider user.uid = auth.uid user.email = auth.info.email user.image = auth.info.image user.password = Devise.friendly_token[0,20] end end I would like to skip confirmation for facebook and google users, where can i put the user.skip_confirmation! Thanks in advance |
How to create and save a predefined checklist collection for users and set up the associations between four models? Posted: 16 May 2016 04:36 AM PDT I'm working on a small project to gain more skill in Ruby an RoR development. Now I got stuck and it drives me crazy. I looked on Stack Overflow and Google for the answer, but I think I'm asking the wrong questions. The idea: - A user can create and login to his account
- The user can create one dashboard with following fields
- Each dashboard contains four predefined checklists (like categories)
- These checklists are displaying a progress of the user that is defined by tasks
- Every checklist contains a collection predefined of tasks (checkboxes)
- The tasks are like to-dos that the user has to complete, so I can updated the progress on the checklist (x of y tasks are complete. xy% done)
- Its the same set of checkboxes for every user
The problem: - My problem is now, how do I create and save the predefined set of tasks for each user, on the creation of the dashboard, with the right associations between the user and checklist model
- Are my associations between the four models right? Is there another or better way to set this up?
Status-Quo: These are associations between the models and the schema. The Rails version is 4.2.6 and Ruby 2.2.3. The app is running in a docker container with postgres. user.rb class User < ActiveRecord::Base has_many :dashboards, dependent: :destroy has_many :tasks, :through => :checklists #Is this right? has_many :identities, dependent: :destroy validates_length_of :dashboards, :maximum => 1 # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :omniauthable, :invitable, :database_authenticatable, :registerable,:recoverable, :rememberable, :trackable end dashboard.rb class Dashboard < ActiveRecord::Base belongs_to :user validates :user_id, presence: true validates_uniqueness_of :title validates_length_of :description, maximum: 300 end task.rb class Task < ActiveRecord::Base belongs_to :checklist belongs_to :user validates :user_id, presence: true validates_uniqueness_of :title validates_length_of :description, maximum: 300 end schema.rb ActiveRecord::Schema.define(version: 20160514200622) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "checklists", force: :cascade do |t| t.string "title" t.string "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "dashboards", force: :cascade do |t| t.string "title" t.string "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "user_id" end add_index "dashboards", ["user_id"], name: "index_dashboards_on_user_id", using: :btree create_table "tasks", force: :cascade do |t| t.string "title" t.string "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.boolean "completed" t.integer "checklist_id" end add_index "tasks", ["checklist_id"], name: "index_tasks_on_checklist_id", using: :btree create_table "users", force: :cascade do |t| t.string "email", default: "" t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "invitation_token" t.datetime "invitation_created_at" t.datetime "invitation_sent_at" t.datetime "invitation_accepted_at" t.integer "invitation_limit" t.integer "invited_by_id" t.string "invited_by_type" t.integer "invitations_count", default: 0 end add_foreign_key "dashboards", "users" add_foreign_key "identities", "users" add_foreign_key "tasks", "checklists" end I will appreciate your help with my problem. |
Unable to make the image a link Posted: 16 May 2016 03:43 AM PDT I get the following error : No route matches {:action=>"show", :controller=>"posts"} missing required keys: [:id] Here is my code <% @posts.each do |x| %> <div class="white"> <%= link_to image_tag x.image.url(:medium), post_path %> <p>Published <%= time_ago_in_words(x.created_at)%>ago</p> <br> |
Poltergeist and phantom render partial with respond_to in controller Posted: 16 May 2016 03:09 AM PDT I have a problem executing my rails app feature files headless. I use phantom as webkit and poltergeist as javascript driver. My feature starts like this: @javascript Scenario: Create a customer Given I am on the "/customers" page When I click on element having id "new_customer" Then I should see "Customer data" The message I get running it is: Then I should see "Customer data" features/step_definitions/feature_steps.rb:16 expected to find text "Customer data" in "LOGOTIMAX :: adminTicketsProjectsCustomersUsermanagementProfileSettingsLog out Listing Customers Show entriesSearch: Id Name 1 Heine 2 IKEA 3 Coca Cola 4 Lufthansa AG 5 Daimler AGShowing 1 to 5 of 5 entriesPrevious1Next New Customer TIMAX - Ruby on Rails application by UniCorp BLOGJIRA" (RSpec::Expectations::ExpectationNotMetError) It seems as if the partial where the text "Customer data" should be displayed does not get rendered by phantom. When I do the same by hand in my browser, it works. Here are the other corresponding files: customers/index.html.erb: <h1>Listing Customers</h1> <div class="grid"> <div class="row cells3 "> <div class="cell" id="customers_list"> <%= render partial: 'customers/list', locals: { customers: @customers } %> </div> <div class="cell colspan2 " id="current_customer"></div> </div> </div> <br> <%= link_to 'New Customer', new_customer_path, class: "button", id: "new_customer", remote: true %> customers_controller.rb (new) def new respond_to do |format| format.js {render layout: false} end end customers/new.html.erb <h1>New Customer</h1> <p>Customer data</p> <%= render 'form' %> customers/new.js.erb $("#current_customer").html("<%= escape_javascript(render partial: 'customers/new' ) %>"); |
Rails instance variables in .js.erb file Posted: 16 May 2016 02:50 AM PDT I have a controller action like this. itineraries_controller.rb def delete_city @new_itinerary = params[:new_itinerary] if params[:new_itinerary].present? @step = params[:step] if @step == 'two' @city = City.find(params[:id]) @delete_rec = true else @city_item = CityItem.find(params[:id]) rescue nil end if @city_item.present? @itinerary = @city_item.country_item.itinerary rescue nil @itinerary = Itinerary.unscoped.find(params[:data_id]) if (@itinerary.present? and @itinerary.user_id == current_user.id) or (current_user.moderator?) @country_item = @city_item.country_item @city_item.destroy @country_item.update_column('city_ids', @country_item.city_items.order(:sequence).pluck(:city_id)) @delete_rec = true end end respond_to do |format| if @delete_rec && @step != 'two' format.js {render 'step_two.js.erb'} elsif @delete_rec && @step == "two" format.js {render 'delete_city_step_2.js.erb'} else format.js {render :text => 'fail'} end end end And js.erb like this: delete_city_step_2.js.erb a = $('a.cityCrossBtn[for='+"<%= @city %>"+']') li = a.closest('.token-input-token-facebook') li.hide(); I am not able to find a element. What is the correct syntax? |
No comments:
Post a Comment