Rails: Assets in manifest file are loaded always? Posted: 10 Jul 2016 07:12 AM PDT The assets required in manifest file app/assets/javascripts/application.js are loaded for all pages? I realized that a script made for me which does something every 5 seconds was being executed in all pages, so now I am not sure if when one requires a script into manifest file, this is loaded in all pages, even if is include just in one view. My manifest file: // app/assets/javascripts/application.js //= require jquery //= require_tree loading/loader My regarding view: / some code = javascript_include_tag "/loading/loader" But the script is executed even in the home. |
How do I install bootstrap js? Posted: 10 Jul 2016 07:20 AM PDT I followed the hartl rails book to install the bootstrap css files, but I believe I'm missing the javascript to go with it. Here's what the book told me to do: - add
bootstrap-sass to the Gemfile: gem 'bootstrap-sass' - run bundle install
add the following to the css: @import "bootstrap-sprockets"; @import "bootstrap";
What else do I need to do to add the javascript portion? |
Rails ecommerce site session Posted: 10 Jul 2016 07:06 AM PDT I have worked through the book Agile Development with Rails 4. I deployed the app using heroku. I only have a login feature for administrators and so anyone can create a cart and submit an order without making an account. I noticed that when i create a cart on my laptop on the deployed website that the cart is the same when i go to my desktop. So there is one cart with say id = 20 shared among all sessions. This is obviously a problem. I suspect it has to do with my module for current_cart but not sure. module CurrentCart extend ActiveSupport::Concern private def set_cart @cart = Cart.find(session[:cart_id]) rescue ActiveRecord::RecordNotFound @cart = Cart.create session[:cart_id] = @cart.id end end I then use include CurrentCart and before_action:set_cart on the store, orders, line items, and carts controllers. I would like each session to be associated with each computer and end upon closing the browser, which I know can vary with the browser settings. I believe this might also be happening because I am storing this information in the database so the cart_id persists until the cart is deleted. Any help would be appreciated. |
Sinatra before filter Posted: 10 Jul 2016 07:13 AM PDT I'm on Sinatra and i don't understand how to deal with my problem: I want to "send" to curl a custom message when he try to go on a wrong path. curl http://localhost:port/blabla It's an error 404 but i want to send him thing like 'error try other path' I tried with this : before'/*' do if (params[:splat].to_s =~ /path_i_want/) != 2 'wrong path' end end or with raise 404 but it doesn't work. Could you help me please ? Regards. |
link to last post - rails Posted: 10 Jul 2016 07:12 AM PDT Im trying to link_to the show action for a post . In my controller I have: @post = Post.all In my view I'm trying to link it to the last post like this: <%= link_to @post.last do %> <%= @post.last.title %> <% end %> But it does not take me to the show page for that post? |
Rails 4: Pass attribute's value into the model for dynamic vailidation Posted: 10 Jul 2016 06:23 AM PDT In my 'Entry' model... class Entry < ActiveRecord::Base ...I am trying to pass an attribute's value directly into the data validation below (the attribute that will dynamically update is ':wpu', and the value is an integer based on the user's form submission. There are three user options from a drop-down menu the will submit a value for ':wpu'; for the sake of this conversation, consider the value either '5', '10', or '20'). validates :text, length: { is: DYNAMIC_VALUE_WOULD_GO_HERE, tokenizer: lambda { |str| str.squish.gsub('&'){''}.scan(/\w+/) } } This validates when the string attribute's word count ':text' is equal to the integer of the other attribute mentioned earlier, ':wpu'. The code above works perfect if I replace the 'DYNAMIC_VALUE_WOULD_GO_HERE' with a '5', '10', or '20', but I haven't been successful in placing a dynamic value in there based on a user's input. I've worked on this thing--probably has a simple answer--for 3 days now, but with no success. Things I have tried: 1) Using attr_reader and calling the attributes value 2) Passing controller method parameters to the model I am open to any suggestions and other methods. I am a beginner in ruby and rails. Here is my full model code as it stands. It doesn't currently work as I haven't been able to pass through 'params'. Otherwise, without trying to make this dynamic, everything works fine if I remove the random experimental method below. class Entry < ActiveRecord::Base belongs_to :story attr_reader :wpu #method used to generate 'wpu' | which is words per user in Story def self.storywpu #story ID from EntriesController current_entry_story_id = Entry.find(params[:id]).story_id #returns 'wpu' | which is words per user in Story storywpu = Story.find(current_entry_story_id).wpu return storywpu end #strips ALL white space before form submission auto_strip_attributes :text, :nullify => false, :squish => true #validates each field has been filled out validates :user_id, presence: true validates :story_id, presence: true validates :text, presence: true, autocomplete: false #validates word count is exactly 'wpu' | which is words per user in Story validates :text, length: { is: self.storywpu, tokenizer: lambda { |str| str.squish.gsub('&'){''}.scan(/\w+/) } } end And here is a related portion of my controller for reference... class EntriesController < ApplicationController before_action :set_entry, only: [:show, :edit, :update, :destroy] def create #New text entry @entry = Entry.create(entry_params) #Related story params @story = Story.find(@entry.story_id) @storyWPU = Story.find(@entry.story_id).wpu @word_count = @entry.text.squish.gsub('&'){''}.scan(/\w+/).size.to_i @wordsLeft = @storyWPU - @word_count if @word_count.nil? @response = 'enter ' + @wordsLeft.to_s + ' words' elsif @wordsLeft == 1 @response = 'enter ' + @wordsLeft.to_s + ' word' elsif @wordsLeft < 0 @response = @wordsLeft.abs.to_s + ' too many!' else @response = 'enter ' + @wordsLeft.to_s + ' words' end respond_to do |format| if @entry.save format.html { redirect_to edit_story_path(@story), notice: 'Nice!' } format.json { render :show, status: :created, location: @entry } else format.html { redirect_to edit_story_path(@story), notice: @response } format.json { render json: @entry.errors, status: :unprocessable_entity } end end end private def set_entry @entry = Entry.find(params[:id]) end private def entry_params params.require(:entry).permit(:text, :user_id, :story_id, :wpu) end end |
Redirect not working in Ruby on Rails Posted: 10 Jul 2016 07:47 AM PDT I have two models, one that is called Timelines and other called Contests. class Contest < ActiveRecord::Base belongs_to :member belongs_to :timeline end class Timeline < ActiveRecord::Base belongs_to :member end While I am inside http://localhost:3000/timelines/1 this path for instance I have a button that when I click it I want to make a redirection to create a new contest. <button type="button" onclick="setContest(0)">Before</button> function setContest(type){ $.ajax({ url: '/contests/new', type: 'GET', data: { "before": type, "timeline_id": $("#timeline_id").text(), "video_id": $("#video_id").text() } }).success(function(d){ location.replace(d.new_path); }).fail(function(err){ alert(err.value); }); } But when I click it I got the following error: ActiveRecord::RecordNotFound in TimelinesController#show Couldn't find Timeline with 'id'=undefined # Use callbacks to share common setup or constraints between actions. def set_timeline @timeline = Timeline.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. Any idea of what might be going on wrong and what can I do to avoid it? Added routes: Prefix Verb URI Pattern Controller#Action leaderboards_show GET /leaderboards/show(.:format) leaderboards#show leaderboards_index GET /leaderboards/index(.:format) leaderboards#index contests GET /contests(.:format) contests#index POST /contests(.:format) contests#create new_contest GET /contests/new(.:format) contests#new edit_contest GET /contests/:id/edit(.:format) contests#edit contest GET /contests/:id(.:format) contests#show PATCH /contests/:id(.:format) contests#update PUT /contests/:id(.:format) contests#update DELETE /contests/:id(.:format) contests#destroy rate POST /rate(.:format) rater#create timelines GET /timelines(.:format) timelines#index POST /timelines(.:format) timelines#create new_timeline GET /timelines/new(.:format) timelines#new edit_timeline GET /timelines/:id/edit(.:format) timelines#edit timeline GET /timelines/:id(.:format) timelines#show PATCH /timelines/:id(.:format) timelines#update PUT /timelines/:id(.:format) timelines#update DELETE /timelines/:id(.:format) timelines#destroy videos GET /videos(.:format) videos#index POST /videos(.:format) videos#create new_video GET /videos/new(.:format) videos#new edit_video GET /videos/:id/edit(.:format) videos#edit video GET /videos/:id(.:format) videos#show PATCH /videos/:id(.:format) videos#update PUT /videos/:id(.:format) videos#update DELETE /videos/:id(.:format) videos#destroy channels GET /channels(.:format) channels#index POST /channels(.:format) channels#create new_channel GET /channels/new(.:format) channels#new edit_channel GET /channels/:id/edit(.:format) channels#edit channel GET /channels/:id(.:format) channels#show PATCH /channels/:id(.:format) channels#update PUT /channels/:id(.:format) channels#update DELETE /channels/:id(.:format) channels#destroy homepage_index GET /homepage/index(.:format) homepage#index mycontests GET /mycontests(.:format) contests#mycontests homepage_store_timeline POST /homepage/store_timeline(.:format) homepage#store_timeline timelinerelatio_create POST /timelinerelatio/create(.:format) timelinerelatio#create add_tag POST /add_tag(.:format) manualvideo#create add_comentary POST /add_comentary(.:format) videocommentary#create addCommentTimeline POST /addCommentTimeline(.:format) timelinecommentary#create orderTimeline POST /orderTimeline(.:format) timelinerelatio#update GET /timelines/:other_param(.:format) timelines#index GET /contests/:other_param(.:format) contests#index root GET / homepage#index new_member_session GET /members/sign_in(.:format) devise/sessions#new member_session POST /members/sign_in(.:format) devise/sessions#create destroy_member_session DELETE /members/sign_out(.:format) devise/sessions#destroy member_password POST /members/password(.:format) devise/passwords#create new_member_password GET /members/password/new(.:format) devise/passwords#new edit_member_password GET /members/password/edit(.:format) devise/passwords#edit PATCH /members/password(.:format) devise/passwords#update PUT /members/password(.:format) devise/passwords#update cancel_member_registration GET /members/cancel(.:format) registrations#cancel member_registration POST /members(.:format) registrations#create new_member_registration GET /members/sign_up(.:format) registrations#new edit_member_registration GET /members/edit(.:format) registrations#edit PATCH /members(.:format) registrations#update PUT /members(.:format) registrations#update DELETE /members(.:format) registrations#destroy Edit code for href: I tried with href but it goes to: http://localhost:3000/timelines/undefined/contests/new?video_id=&timeline_id=&before=0 instead of http://localhost:3000/contests/new?video_id=&timeline_id=&before=0 I tried with href but it goes to: http://localhost:3000/timelines/undefined/contests/new?video_id=&timeline_id=&before=0 instead of http://localhost:3000/contests/new?video_id=&timeline_id=&before=0 Here is the code: function setContest(type){ var URL; var timeline_id=$("#timeline_id").text(); var video_id= $("#video_id").text(); URL+="/contests/new?video_id=" + video_id + '&timeline_id=' + timeline_id + '&before=' + type; return URL; } <a href="javascript:window.location=setContest(0);">Before</a> |
Active Admin username and password Posted: 10 Jul 2016 06:59 AM PDT I have successfully installed Active Admin on my C9 Ruby on Rails environment but when I entered the default username and password, it came back as "Invalid Email or password." I read so many posts on Active Admin but nothing was related to my issue. Can someone help? - a. gem 'activeadmin', github: 'activeadmin'
- b. Bundle install
- c. rails generate active_admin:install
- d. start the server
- e. /admin and login screen appeared.
|
ActiveRecord::Rollback doesn't seems to do a transaction rollback Posted: 10 Jul 2016 05:14 AM PDT One day I noticed my transactions dont accept a ActiveRecord::Rollback. I have such an example: example ActiveRecord::Base.transaction do puts @shipment_list.status @shipment_list.update(shipment_list_params) raise ActiveRecord::Rollback end puts @shipment_list.status result CACHE (0.0ms) SELECT `shipment_lists`.* FROM `shipment_lists` WHERE `shipment_lists`.`id` = 24121 ORDER BY created_at DESC LIMIT 1 [["id", "24121"]] (0.2ms) BEGIN reserve (1.3ms) SELECT MAX(`audits`.`version`) AS max_id FROM `audits` WHERE `audits`.`auditable_id` = 24121 AND `audits`.`auditable_type` = 'ShipmentList' SQL (160.5ms) INSERT INTO `audits` (`action`, `auditable_id`, `auditable_type`, `audited_changes`, `created_at`, `remote_address`, `request_uuid`, `user_id`, `user_type`, `version`) VALUES ('update', 24121, 'ShipmentList', '---\nstatus:\n- reserve\n- 2\n', '2016-07-10 12:01:55', '127.0.0.1', 'efc5b6e7-c3f9-4b4a-a0fd-67651b2eeb20', 18, 'User', 19) SQL (0.3ms) UPDATE `shipment_lists` SET `status` = 2, `updated_at` = '2016-07-10 12:01:55' WHERE `shipment_lists`.`id` = 24121 (0.2ms) ROLLBACK bill Where is the mistake? I really in a trouble. |
Refactor controller action code DRY Posted: 10 Jul 2016 05:48 AM PDT I am using indeed_api to retrieve jobs from Indeed API, but because Indeed only allows 25 results per query, i have come up with this code in my controller to get all jobs and list them all on one page: @jobs = IndeedAPI.search_jobs(co: "au", l: "sydney", radius: "100", sort: "date", limit: "25") @results = @jobs.results if @jobs.total_results > 25 @jobs2 = IndeedAPI.search_jobs(co: "au", l: "sydney", radius: "100", sort: "date", start: "25", limit: "25") @results += @jobs2.results end if @jobs.total_results > 50 @jobs3 = IndeedAPI.search_jobs(co: "au", l: "sydney", radius: "100", sort: "date", start: "50", limit: "25") @results += @jobs3.results end if @jobs.total_results > 75 @jobs4 = IndeedAPI.search_jobs(co: "au", l: "sydney", radius: "100", sort: "date", start: "75", limit: "25") @results += @jobs4.results #and so on... This is rather ugly and definitely not a rails way to do it. I mean, the controller could spread out to hundreds of lines. Is there a way to put this code in a loop or refactor it in any other way? |
Associate rails api and ember Posted: 10 Jul 2016 06:18 AM PDT On submitting, my Ember frontend is sending me data like this: { "data":{ "attributes":{ "title":"asd", "description":"asd" }, "relationships":{ "users":{ "data":[ { "type":"users", "id":"1" } ] } }, "type":"cards" } } Here, I want to associate between a card and a user when a new card is created. app/controllers/cards_controller.rb def create @card = Card.new(card_params) if @card.save @card.users << User.find(params[:data][:relationships][:users][:data]) if params[:data][:relationships][:users][:data] render json: @card else render json: @card, :status => 422 end end private def card_params params.require(:data).require(:attributes).permit(:title, :description) end The error in the Rails end is something like this: DEPRECATION WARNING: Method to_a is deprecated and will be removed in Rails 5.1, as `ActionController::Parameters` no longer inherits from hash. Using this deprecated behavior exposes potential security problems. If you continue to use this method you may be creating a security vulnerability in your app that can be exploited. Instead, consider using one of these documented methods which are not deprecated: http://api.rubyonrails.org/v5.0.0/classes/ActionController/Parameters.html (called from create at /Applications/AMPPS/www/development/ideast/hub/hub-server/app/controllers/cards_controller.rb:16) Completed 500 Internal Server Error in 24ms (ActiveRecord: 3.4ms) NoMethodError (undefined method `join' for #<ActionController::Parameters:0x007f9b5549e380> Did you mean? JSON): Repo link: https://github.com/ghoshnirmalya/hub-server |
Link to tab in other page using link_to in rails 4 Posted: 10 Jul 2016 04:50 AM PDT How do you link to a different page and activating a tab using link_to from the scaffold generated code. <%= link_to t('.cancel', :default => t("helpers.links.cancel")), root_path, :class => 'btn btn-default' %> i tried this but it didn't work either: <%= link_to t('.cancel', :default => t("helpers.links.cancel")), root_path('#panel_projects'), :class => 'btn btn-default' %> Where as #panel_projects is the tab link which i want the users to get to after getting redirected. Does anybody know how to accomplish this? Preferably without Javascript. |
Rspec testing inside a loop Posted: 10 Jul 2016 07:21 AM PDT I am trying to test the code inside a loop, how would I go about this: class MyClass def initialize(topics, env, config, limit) @client = Twitter::Streaming::Client.new(config) @topics = topics @env = env @limit = limit end def start @client.filter(track: @topics.join(",")) do |object| # how would I test the code inside here, basically logical stuff next if !object.is_a?(Twitter::Tweet) txt = get_txt(object.text) end end Is there a way to do this? |
Configuring Puma and Sidekiq Posted: 10 Jul 2016 03:22 AM PDT Might be more of trying to overcome a learning curve + actual code question. I apologize if it seems nubish, currently I get this error within production. Basically I keep recieving this "redis pool is too small" and I'm lost where to start, I'm actually lost on basically understanding how to accurately configure sidekiq with puma or anything that comes after configuration like scaling etc. Below I have my configuration followed my error I recieve . ProcFile web: bundle exec puma -C config/puma.rb worker: bundle exec sidekiq -e production -C config/sidekiq.yml Sidekiq init if Rails.env.production? Sidekiq.configure_client do |config| config.redis = { url: ENV['REDIS_URL'], size: 2 } end Sidekiq.configure_server do |config| config.redis = { url: ENV['REDIS_URL'], size: 20 } Rails.application.config.after_initialize do Rails.logger.info("DB Connection Pool size for Sidekiq Server before disconnect is: #{ActiveRecord::Base.connection.pool.instance_variable_get('@size')}") ActiveRecord::Base.connection_pool.disconnect! ActiveSupport.on_load(:active_record) do config = Rails.application.config.database_configuration[Rails.env] config['reaping_frequency'] = ENV['DATABASE_REAP_FREQ'] || 10 # seconds # config['pool'] = ENV['WORKER_DB_POOL_SIZE'] || Sidekiq.options[:concurrency] config['pool'] = 16 ActiveRecord::Base.establish_connection(config) Rails.logger.info("DB Connection Pool size for Sidekiq Server is now: #{ActiveRecord::Base.connection.pool.instance_variable_get('@size')}") end end end end redis init if ENV["REDISTOGO_URL"] $redis = Redis.new(:url => ENV["REDISTOGO_URL"]) end puma.rb workers Integer(ENV['WEB_CONCURRENCY'] || 2) threads_count = Integer(ENV['MAX_THREADS'] || 1) threads threads_count, threads_count preload_app! rackup DefaultRackup port ENV['PORT'] || 3000 environment ENV['RACK_ENV'] || 'development' # Because we are using preload_app, an instance of our app is created by master process (calling our initializers) and then memory space # is forked. So we should close DB connection in the master process to avoid connection leaks. # https://github.com/puma/puma/issues/303 # http://stackoverflow.com/questions/17903689/puma-cluster-configuration-on-heroku # http://www.rubydoc.info/gems/puma/2.14.0/Puma%2FDSL%3Abefore_fork # Dont have to worry about Sidekiq's connection to Redis because connections are only created when needed. As long as we are not # queuing workers when rails is booting, there will be no redis connections to disconnect, so it should be fine. before_fork do puts "Puma master process about to fork. Closing existing Active record connections." ActiveRecord::Base.connection.disconnect! end on_worker_boot do # Worker specific setup for Rails 4.1+ # See: https://devcenter.heroku.com/articles/deploying-rails-applications-with-the-puma-web-server#on-worker-boot ActiveRecord::Base.establish_connection end error in logs Your Redis connection pool is too small for Sidekiq to work. Your pool has 20 connections but really needs to have at least 22 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/sidekiq-4.1.4/lib/sidekiq/redis_connection.rb:38:in `verify_sizing' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/sidekiq-4.1.4/lib/sidekiq/redis_connection.rb:17:in `create' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/sidekiq-4.1.4/lib/sidekiq.rb:128:in `redis=' 10:04:44 worker.1 | /home/ubuntu/workspace/sample_v1/config/initializers/sidekiq.rb:10:in `block in <top (required)>' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/sidekiq-4.1.4/lib/sidekiq.rb:70:in `configure_server' 10:04:44 worker.1 | /home/ubuntu/workspace/sample_v1/config/initializers/sidekiq.rb:9:in `<top (required)>' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `block in load' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:652:in `block in load_config_initializer' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/notifications.rb:166:in `instrument' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:651:in `load_config_initializer' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:616:in `block (2 levels) in <class:Engine>' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:615:in `each' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/engine.rb:615:in `block in <class:Engine>' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `instance_exec' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:30:in `run' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:55:in `block in run_initializers' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:44:in `each' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:44:in `tsort_each_child' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:415:in `call' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `call' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each' 10:04:44 worker.1 | /usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/initializable.rb:54:in `run_initializers' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/railties-4.2.6/lib/rails/application.rb:352:in `initialize!' 10:04:44 worker.1 | /home/ubuntu/workspace/sample_v1/config/environment.rb:5:in `<top (required)>' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `block in require' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:274:in `require' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/sidekiq-4.1.4/lib/sidekiq/cli.rb:237:in `boot_system' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/sidekiq-4.1.4/lib/sidekiq/cli.rb:50:in `run' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/sidekiq-4.1.4/bin/sidekiq:12:in `<top (required)>' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/bin/sidekiq:23:in `load' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/bin/sidekiq:23:in `<top (required)>' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/lib/bundler/cli/exec.rb:63:in `load' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/lib/bundler/cli/exec.rb:63:in `kernel_load' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/lib/bundler/cli/exec.rb:24:in `run' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/lib/bundler/cli.rb:304:in `exec' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/lib/bundler/vendor/thor/lib/thor/command.rb:27:in `run' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/lib/bundler/vendor/thor/lib/thor/invocation.rb:126:in `invoke_command' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/lib/bundler/vendor/thor/lib/thor.rb:359:in `dispatch' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/lib/bundler/vendor/thor/lib/thor/base.rb:440:in `start' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/lib/bundler/cli.rb:11:in `start' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/exe/bundle:27:in `block in <top (required)>' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/lib/bundler/friendly_errors.rb:98:in `with_friendly_errors' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/gems/bundler-1.12.3/exe/bundle:19:in `<top (required)>' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/bin/bundle:23:in `load' 10:04:44 worker.1 | /usr/local/rvm/gems/ruby-2.3.0/bin/bundle:23:in `<main>' 10:04:45 worker.1 | exited with code 1 10:04:45 system | sending SIGTERM to all processes Any help or sort of guidance will be amazing. |
your RubyGems configuration, which is usually located in ~/.gemrc, contains invalid YAML syntax Posted: 10 Jul 2016 02:55 AM PDT i have installed rails software while creating new project i am facing an error plz help me... C:\Sites>rails new satya create create README.rdoc create Rakefile create config.ru create .gitignore create Gemfile create app create app/assets/javascripts/application.js create app/assets/stylesheets/application.css create app/controllers/application_controller.rb create app/helpers/application_helper.rb create app/views/layouts/application.html.erb create app/assets/images/.keep create app/mailers/.keep create app/models/.keep create app/controllers/concerns/.keep create app/models/concerns/.keep create bin create bin/bundle create bin/rails create bin/rake create bin/setup create config create config/routes.rb create config/application.rb create config/environment.rb create config/secrets.yml create config/environments create config/environments/development.rb create config/environments/production.rb create config/environments/test.rb create config/initializers create config/initializers/assets.rb create config/initializers/backtrace_silencers.rb create config/initializers/cookies_serializer.rb create config/initializers/filter_parameter_logging.rb create config/initializers/inflections.rb create config/initializers/mime_types.rb create config/initializers/session_store.rb create config/initializers/wrap_parameters.rb create config/locales create config/locales/en.yml create config/boot.rb create config/database.yml create db create db/seeds.rb create lib create lib/tasks create lib/tasks/.keep create lib/assets create lib/assets/.keep create log create log/.keep create public create public/404.html create public/422.html create public/500.html create public/favicon.ico create public/robots.txt create test/fixtures create test/fixtures/.keep create test/controllers create test/controllers/.keep create test/mailers create test/mailers/.keep create test/models create test/models/.keep create test/helpers create test/helpers/.keep create test/integration create test/integration/.keep create test/test_helper.rb create tmp/cache create tmp/cache/assets create vendor/assets/javascripts create vendor/assets/javascripts/.keep create vendor/assets/stylesheets create vendor/assets/stylesheets/.keep run bundle install Your RubyGems configuration, which is usually located in ~/.gemrc, contains invalid YAML syntax. ------------------------------------------------------------------------ the above error i am getting ... |
I need to create a dropdown menu in Rails for tshirt sizes that are varying in stock Posted: 10 Jul 2016 02:39 AM PDT I need to create a dropdown menu for varying tshirt sizes, some of the sizes stock are 0, so if the item has 0 stock it would not show up or be blank etc. I am loading the data from a csv in Rails. Sidenote: Is this better suited for javascript? Current Products Controller: def fetch_products @products=[] CSV.foreach("cc_inventory.csv", headers:true) do |row| product=Product.new product.pid = row.to_h["pid"] product.item = row.to_h["item"] product.description = row.to_h["description"] product.price = row.to_h["price"] product.img_file = row.to_h["img_file"] product.category = row.to_h["category"] product.xs = row.to_h["xs"] product.s = row.to_h["s"] product.m = row.to_h["m"] product.l = row.to_h["l"] product.xl = row.to_h["xl"] @products << product end @products end HTML: <select class="turnintodropdown" name=""> <option value="" disabled selected>Select your Size</option> <option value=xs>xs</option> <option value=s>s</option> <option value=m>m</option> <option value=l>l</option> <option value=xl>xl</option> </select> I have not had a lot of experience with dropdowns and with rails, I am not specifically sure how to setup the CSV for the sizes properly. Current CSV: pid,item,description,price,img_file,category,xs,s,m,l,xl 101,Dope White,DOPE Unisex White Preshrunk Cotton Tee,21,dope_white,apparel,0,2,4,5,3 102,Dope Grey,DOPE Women's Fitted Organic Preshrunk Cotton Grey Tee,21,dope_grey,apparel,2,6,0,0,0 103,Drake & 40 Black,Drake Unisex Cotton Black Tee,21,drake_black,apparel,2,2,1,2,1 104,Drake & 40 Navy,Drake Women's Fitted Organic Cotton Navy Tee,21,drake_navy,apparel,2,19,0,3,0 105,H-Town Vicious Black,H-Town Vicious Women's Cotton Fitted White Tee,21,htown_vicious_black,apparel,4,5,4,5,3 106,H-Town Vicious White,H-Town Vicious Women's Cotton Black Tee,16,htown_vicious_white,apparel,4,0,0,0,0 |
Create associated records when creating a user with Devise taking an attribute for the associated record Posted: 10 Jul 2016 05:37 AM PDT I have a user model and through the model membership, it has many organizations: class User < ActiveRecord::Base has_many :memberships has_many :organizations, through: :memberships end class Membership < ActiveRecord::Base belongs_to :user belongs_to :organization end class Organization < ActiveRecord::Base has_many :memberships has_many :users, through: :memberships end During the signup process, I want to ask for the name of my organization, so, my form looks like this: = simple_for_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| = devise_error_messages! = f.simple_fields_for :memberships do |fm| = fm.input :kind, as: :hidden, input_html: {value: Membership::OWNER} = fm.simple_fields_for :organization do |fo| = fo.input :name, required: false, label: "Organization" = f.input :name = f.input :email = f.input :password = f.input :password_confirmation and my custom strong params definition in my custom Devise registration controller looks like this: def configure_sign_up_params devise_parameter_sanitizer.permit(:sign_up) do |u| u.permit(:email, :password, :password_confirmation, memberships: {organizations: [:name]}) end end When I submit the form, I get this error: Membership(#70355446274100) expected, got Array(#70355394078720) on Devise's create controller action. The parameters look like this: {"utf8"=>"✓", "authenticity_token"=>"...", "user"=> {"memberships"=> {"kind"=>"owner", "organizations"=>{"name"=>"Organization name"}}, "name"=>"User's Name", "email"=>"email@address.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"} If I add accepts_nested_attributes_for :memberships accepts_nested_attributes_for :organizations to the user model or if I add: accepts_nested_attributes_for :memberships to the user model and accepts_nested_attributes_for :organizations to the membership model, the membership and organization simple disappear for the form, they are not rendered. Even when my new registration controller action looks like this: def new super resource.memberships.build.build_organization end I also tried defining my strong params as this: def configure_sign_up_params devise_parameter_sanitizer.permit(:sign_up) do |u| u.permit(:email, :password, :password_confirmation, memberships_attributes: [:id, organization_attributess: [:id, :name]]) end end and it (obviously) made no difference in the HTML input field not appearing. What am I missing? How can I make this work? In regards to this question being a duplicate of Expected ProductField, got array issue , nowhere in that question or answers is the matter of forms addressed, which I am addressing here. |
Get css file which used in desired url of webpage in ruby on rails Posted: 10 Jul 2016 02:29 AM PDT Currently, I'm making web app which requires to display desired webpage inline. The app can now get html file from desired url of webpage but since app is not loading css file, layout is broken. Now I want app to get css file(or file path) which used in desired webpage and load it with html that app get at same time. How I can do it? |
Error message when running "rails new myapp" command with byebug Posted: 10 Jul 2016 01:38 AM PDT when making a new ruby on rails app via my terminal, by the command "rails new newapp" I find the following error message in my terminal. It seems linked difficulties with installing bye bug 9.0.5. After a while the terminal says it can not succeed before bundling. I suppose this a major barrier to the correct development of my app. Can anyone help? I am attaching the relevant terminal statements and highlight in bold what I think where the problem is. Fetching gem metadata from https://rubygems.org/ Fetching version metadata from https://rubygems.org/ Fetching dependency metadata from https://rubygems.org/ Resolving dependencies...... Using rake 11.2.2 Using i18n 0.7.0 Using json 1.8.3 Using minitest 5.9.0 Using thread_safe 0.3.5 Using builder 3.2.2 Using erubis 2.7.0 Using mini_portile2 2.1.0 Using pkg-config 1.1.7 Using rack 1.6.4 Using mime-types-data 3.2016.0521 Using arel 6.0.3 Using debug_inspector 0.0.2 Using bundler 1.12.5 Installing byebug 9.0.5 with native extensions Gem::Ext::BuildError: ERROR: Failed to build gem native extension. /Users/nicholaswenzel/.rbenv/versions/2.2.3/bin/ruby -r ./siteconf20160710-36604-3ys7vr.rb extconf.rb creating Makefile make "DESTDIR=" clean xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun make "DESTDIR=" xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun make failed, exit code 1 Gem files will remain installed in /Users/nicholaswenzel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/byebug-9.0.5 for inspection. Results logged to /Users/nicholaswenzel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-15/2.2.0-static/byebug-9.0.5/gem_make.out Using coffee-script-source 1.10.0 Using execjs 2.7.0 Using thor 0.19.1 Using concurrent-ruby 1.0.2 Using multi_json 1.12.1 Using sass 3.4.22 Using tilt 2.0.5 Using spring 1.7.2 Using sqlite3 1.3.11 Using turbolinks-source 5.0.0 Using rdoc 4.2.2 Using tzinfo 1.2.2 Installing nokogiri 1.6.8 with native extensions Gem::Ext::BuildError: ERROR: Failed to build gem native extension. /Users/nicholaswenzel/.rbenv/versions/2.2.3/bin/ruby -r ./siteconf20160710-36604-1ukclqg.rb extconf.rb Using pkg-config version 1.1.7 checking if the C compiler accepts ... *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/Users/nicholaswenzel/.rbenv/versions/2.2.3/bin/$(RUBY_BASE_NAME) --help --clean /Users/nicholaswenzel/.rbenv/versions/2.2.3/lib/ruby/2.2.0/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError) You have to install development tools first. from /Users/nicholaswenzel/.rbenv/versions/2.2.3/lib/ruby/2.2.0/mkmf.rb:571:in `block in try_compile' from /Users/nicholaswenzel/.rbenv/versions/2.2.3/lib/ruby/2.2.0/mkmf.rb:522:in `with_werror' from /Users/nicholaswenzel/.rbenv/versions/2.2.3/lib/ruby/2.2.0/mkmf.rb:571:in `try_compile' from extconf.rb:138:in `nokogiri_try_compile' from extconf.rb:162:in `block in add_cflags' from /Users/nicholaswenzel/.rbenv/versions/2.2.3/lib/ruby/2.2.0/mkmf.rb:619:in `with_cflags' from extconf.rb:161:in `add_cflags' from extconf.rb:414:in `<main>' extconf failed, exit code 1 Gem files will remain installed in /Users/nicholaswenzel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/nokogiri-1.6.8 for inspection. Results logged to /Users/nicholaswenzel/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/extensions/x86_64-darwin-15/2.2.0-static/nokogiri-1.6.8/gem_make.out Using rack-test 0.6.3 Using mime-types 3.1 Using binding_of_caller 0.7.2 An error occurred while installing byebug (9.0.5), and Bundler cannot continue. Make sure that `gem install byebug -v '9.0.5'` succeeds before bundling. run bundle exec spring binstub --all * bin/rake: spring inserted * bin/rails: spring inserted Nicholass-MacBook-Pro:installmaster nicholaswenzel$ |
Rails + ionic : input from ionic to rails backend = Can't verify CSRF token authenticity 400 bad request Posted: 10 Jul 2016 01:18 AM PDT I have an app both in ionic and rails. the idea is to have the rails as the backend, and ionic as the interface. I use jsonapi_resources gem for this project. the request works well in postman, however it keep gives me cors-preflight error. So I managed to resolve that by using rack-cors gem. Now the request do get through the rails app, now it just that I keep getting this csrf error. application_controller.rb class ApplicationController < JSONAPI::ResourceController # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :null_session before_filter :allow_ajax_request_from_other_domains after_filter :set_csrf_cookie_for_ng def allow_ajax_request_from_other_domains headers['Access-Control-Allow-Origin'] = 'http://localhost:8100/' headers['Access-Control-Request-Method'] = '*' headers['Access-Control-Allow-Headers'] = '*' headers['Access-Control-Allow-Methods'] = 'GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD' end def set_csrf_cookie_for_ng cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery? end protected # In Rails 4.2 and above def verified_request? super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN']) end # In Rails 4.1 and below def verified_request? super || form_authenticity_token == request.headers['X-XSRF-TOKEN'] end end app.js .config(function($stateProvider, $urlRouterProvider, $httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common["X-Requested-With"]; ...(routing details here)}) parts where I capture the input and post to the rails app: $scope.item = {}; $scope.post = function(item){ $http({ method: 'POST', url: 'http://localhost:3000/tests', data: {"type":"tests", "attributes":{"names":"test from the other side"}}, headers: {'Content-Type': 'application/vnd.api+json', 'Accept': 'application/vnd.api+json' } }) console.log(item) } route.rb Rails.application.routes.draw do # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". jsonapi_resources :tests # You can have the root of your site routed with "root" root 'welcome#index' end I have tried searching for answer, but I kept getting this error. |
RailsTutorial Chapter 8 Tests Failing Posted: 10 Jul 2016 12:39 AM PDT I am working through chapter 8 of Michael Hartl's Rails tutorial (www.railstutorial.org) and have encountered failing tests (both failures and errors). I've spent several hours trying to get these tests to pass, and have read similar questions on StackOverflow, but none of the answers have fixed my problem. Here are the messages for the failing tests: 1) Failure: UsersSignupTest#test_valid_signup_information [/home/ubuntu/workspace/test/integration/users_signup_test.rb:25]: expecting <"users/show"> but rendering with <["statics/home", "layouts/_shim", "layouts/_header", "layouts/_footer", "layouts/application"]> 2) Error: UsersLoginTest#test_login_with_valid_information_followed_by_logout: NoMethodError: undefined method `[]' for nil:NilClass app/controllers/sessions_controller.rb:7:in `create' test/integration/user_login_test.rb:21:in `block in <class:UsersLoginTest>' 3) Error: UsersLoginTest#test_login_with_invalid_information: NoMethodError: undefined method `[]' for nil:NilClass app/controllers/sessions_controller.rb:7:in `create' test/integration/user_login_test.rb:12:in `block in <class:UsersLoginTest>' And related files: users_signup_test.rb require 'test_helper' class UsersSignupTest < ActionDispatch::IntegrationTest test "invalid signup information" do get signup_path assert_no_difference 'User.count' do post users_path, user: { name: "", email: "user@invalid", password: "foo", password_confirmation: "bar" } end assert_template 'users/new' end test "valid signup information" do get signup_path assert_difference 'User.count', 1 do post users_path, user: { name: "Example User", email: "user@stpauls.school.nz", password: "password", password_confirmation: "password" } end follow_redirect! assert_template 'users/show' assert is_logged_in? end end user_login_test.rb require 'test_helper' class UsersLoginTest < ActionDispatch::IntegrationTest def setup @user = users(:someName) end test "login with invalid information" do get login_path assert_template 'sessions/new' post login_path, params: { session: { email: "", password: "" } } assert_template 'sessions/new' assert_not flash.empty? get root_path assert flash.empty? end test "login with valid information followed by logout" do get login_path post login_path, params: { session: { email: @user.email, password: 'password' } } assert is_logged_in? assert_redirected_to @user follow_redirect! assert_template 'users/show' assert_select "a[href=?]", login_path, count: 0 assert_select "a[href=?]", logout_path assert_select "a[href=?]", user_path(@user) delete logout_path assert_not is_logged_in? assert_redirected_to root_url follow_redirect! assert_select "a[href=?]", login_path assert_select "a[href=?]", logout_path, count: 0 assert_select "a[href=?]", user_path(@user), count: 0 end end sessions_controller.rb class SessionsController < ApplicationController def new end def create user = User.find_by(email: params[:session][:email].downcase) if user && user.authenticate(params[:session][:password]) log_in user redirect_to root_url else flash.now[:danger] = 'Invalid email/password combination' render 'new' end end def destroy log_out flash.now[:success] = 'Successfully logged out!' redirect_to root_url end end test_helper.rb ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. fixtures :all # Add more helper methods to be used by all tests here... def is_logged_in? !session[:user_id].nil? end def log_in_as(user, options = {}) password = options[:password] || 'example' end end sessions_helper.rb module SessionsHelper # Logs in the given user. def log_in(user) session[:user_id] = user.id end # Returns the current logged-in user (if any). def current_user @current_user ||= User.find_by(id: session[:user_id]) end # Returns true if the user is logged in, false otherwise. def logged_in? !current_user.nil? end # Logs out the current user. def log_out session.delete(:user_id) @current_user = nil end end users.yml somename: name: "SomeName" email: "somename@someemail.com" password_digest: <%= User.digest('password') %> As I've said, I've spent a long time trying to fix these errors with no luck. Any help is appreciated! It's also worth mentioning that I've been changing the names/values of some variables throughout, but I believe I've been consistent in the renaming so this shouldn't be affecting anything. Sorry for the superlong post. |
View rails record details in bootstrap modal on row click Posted: 09 Jul 2016 11:18 PM PDT I have been stuck on this problem for quite some time now and looked through several posts as well, however I cannot achieve exactly what I want for my Rails application. Essentially, I want to be able to click on a table row on my page and have a modal pop up which displays all the information for that specific record. Here are the scenarios which I have thought of/attempted partially: - Set the data-link attribute in table row with some JS as follows
HTML: <tr data-link="<%= kid_path %>"> ... </tr> JS: $("tr[data-link]").dblclick(function() { window.location = $(this).data("link") }) This worked fine to open the show path page generated by the scaffold, but I was not able to modify it to work with a modal and have the same data for the kid in the modal. - Use data-id and JavaScript to load onto the modal
HTML: <tr data-id="<%= kid.id %>"> ... </tr> JS: $(function () { $('#showModal').modal({ keyboard: true, backdrop: "static", show: false, }).on('show', function () { }); $(".table-striped").find('tr[data-id]').on('click', function () { debugger; $('#showDetails').html($('<p>' + 'Kid ID: ' + $(this).data('id') + '<%= Kid.find(30).first_name %>' + '</p>')); $('#showModal').modal('show'); }); }); In this approach I am able to load the modal on row click and am able to access the Kid ID, however I cannot move further to access other attributes of the record. For example, I want to set @Kid = kid.find(id) using JS where id would be the extracted ID from the row. And then, I want to be able to write the generic modal template which displays other elements (ex. kid.first_name, kid.last_name, etc). I am totally stuck and cannot find any approach that helps to accomplish my goal. Any help is appreciated, thank you. |
Associations in Rails 4 Posted: 09 Jul 2016 11:21 PM PDT I am developing a web application for task management using ruby on rails. I have two models user and task . The models look like this class User < ActiveRecord::Base has_many :tasks devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable def role?(role_name) role == role_name end def self.assigned_user(task_params) User.where("name = ?", task_params["assigned_to"]) end end class Task < ActiveRecord::Base belongs_to :user end what i want is assign task to user when a task is created. But i don't know how to do it in create action of tasks_controller . My create action looks like this def create @task = Task.new(task_params) respond_to do |format| if @task.save @user = User.assigned_user(task_params) @user.tasks << Task.last format.html { redirect_to @task, notice: 'Task was successfully created.' } format.json { render :show, status: :created, location: @task } else format.html { render :new } format.json { render json: @task.errors, status: :unprocessable_entity } end end end Whenever admin assigns a task when its created, it gives an error saying undefined method tasks for #<User::ActiveRecord_Relation:0x007fe7b1c60610> . Does anyone can help what can be the problem with this? |
Rails, search with Ransack gem, downcase a string Posted: 09 Jul 2016 10:54 PM PDT I am trying to write a search form for my shops using ransack. Currently, I can search using the name_or_address_cont option which looks EITHER in the name OR in the address. If I had a shop Adidas in London and I type Adidas London there would be no results. Therefore I looked for a way to concatenate the two attributes and search by the new one. What I found in some old posts was the following code: ransacker :search_name, :formatter => proc {|v| UnicodeUtils.downcase(v) } do |parent| Arel::Nodes::NamedFunction.new('LOWER', [Arel::Nodes::NamedFunction.new('concat_ws', [' ', parent.table[:name], parent.table[:address], parent.table[:id]])] ) end Which is supposed to search by a shop's name, address, and id. However, when I run I get an error in the UnicodeUtils. I tried changing it to v.downcase! but I get another error. Any idea how to handle this problem? Thank you! |
Is it possible to convert the complex SQL into rails? Posted: 10 Jul 2016 12:38 AM PDT SPEC I need to pick all rooms that don't have a single day with saleable = FALSE in the requested time period(07-09 ~ 07-19) : I have a table room with 1 row per room. I have a table room_skus with one row per room and day (complete set for the relevant time range). The column saleable is boolean NOT NULL and date is defined date NOT NULL SELECT id FROM room r WHERE NOT EXISTS ( SELECT 1 FROM room_skus WHERE date BETWEEN '2016-07-09' AND '2016-07-19' AND room_id = r.id AND NOT saleable GROUP BY 1 ); The above SQL query is working, but I wonder how could I translate it into Rails ORM. |
Rails association class Posted: 10 Jul 2016 12:50 AM PDT i try to create an association class with Ruby on Rails but but it does not work. I need to do this : I have create my models but I'm not sure I did it right Someone here can explain me from the beginning ? class CreateJobsUsers < ActiveRecord::Migration def change create_table :jobs_users, id: false do |t| t.belongs_to :jobs, index: true t.belongs_to :users, index: true t.integer :level end end end |
Cloudinary image transformation parameters not working in Rails app Posted: 09 Jul 2016 09:47 PM PDT Here's the code: = link_to (cl_image_tag(post.image_url, width:640, quality:30, class: "img-responsive")), post_path(post) As mentioned here, this should give me an image with quality set to 30, but I'm not seeing the change in quality of the images on the site. I've tried different values for quality ranging from 10 to 100 but I'm not seeing even a slight difference. I also tried other parameters, for example, format: "jpg" , which is supposed to force convert all non-jpg files to jpg, but it isn't working either. The width param works fine, by the way. |
sqlite3.rb:6:in require: libruby.so.2.2: cannot open shared object file Posted: 09 Jul 2016 08:50 PM PDT sorry for my english. I was learning about ruby on rails and i tried to update to rails 5. I uninstall olders version of ruby and now i have problems. i have reading http://railsapps.github.io/updating-rails.html i made a mistake because i uninstalled something that i dint do. now i have ruby-2.3.1 i have this error now. .gem/gems/sqlite3-1.3.11/lib/sqlite3.rb:6:in `require': libruby.so.2.2: cannot open shared object file: No such file or directory - /home/yvasquez/.gem/gems/sqlite3-1.3.11/lib/sqlite3/sqlite3_native.so (LoadError) Thanks for reply |
Rails app javascript stopped working in production Posted: 09 Jul 2016 08:44 PM PDT My blog page works fine in development environment,but stopped work in production environment. The HTML code: <div class="col-md-2" id="quicktags-block"> <div id="quicktags" class="pull-right"> <script type="text/javascript">edToolbar('article_body_and_extended', '#<TextFilter:0x00000006d24de8>');</script> </div> </div> This code was used to show the rich text editor. In development environment ,the code is like this: function edToolbar(which, textfilter) { get_buttons(textfilter); document.write('<div id="ed_toolbar_' + which + '" class="btn-toolbar"><div class="btn-group-vertical">'); for (i = 0; i < extendedStart; i++) { edShowButton(which, edButtons[i], i); } for (i = extendedStart; i < edButtons.length; i++) { edShowButton(which, edButtons[i], i); } if (edShowExtraCookie()) { document.write( '<input type="button" id="ed_close_' + which + '" class="btn btn-default" onclick="edCloseAllTags(\'' + which + '\');" value="Close Tags" />' + '<input type="button" id="ed_spell_' + which + '" class="btn btn-default" onclick="edSpell(\'' + which + '\');" value="Dict" />' ); } else { document.write( '<input type="button" id="ed_close_' + which + '" class="btn btn-default" onclick="edCloseAllTags(\'' + which + '\');" value="Close Tags" />' + '<input type="button" id="ed_spell_' + which + '" class="btn btn-default" onclick="edSpell(\'' + which + '\');" value="Dict" />' ); } // edShowLinks(); document.write('</div></div>'); edOpenTags[which] = new Array(); } In production environment,the code is different: function edToolbar(e, t) { for (get_buttons(t), document.write('<div id="ed_toolbar_' + e + '" class="btn-toolbar"><div class="btn-group-vertical">'), i = 0; i < extendedStart; i++) edShowButton(e, edButtons[i], i); for (i = extendedStart; i < edButtons.length; i++) edShowButton(e, edButtons[i], i); edShowExtraCookie() ? document.write('<input type="button" id="ed_close_' + e + '" class="btn btn-default" onclick="edCloseAllTags(\'' + e + '\');" value="Close Tags" /><input type="button" id="ed_spell_' + e + '" class="btn btn-default" onclick="edSpell(\'' + e + '\');" value="Dict" />') : document.write('<input type="button" id="ed_close_' + e + '" class="btn btn-default" onclick="edCloseAllTags(\'' + e + '\');" value="Close Tags" /><input type="button" id="ed_spell_' + e + '" class="btn btn-default" onclick="edSpell(\'' + e + '\');" value="Dict" />'), document.write("</div></div>"), edOpenTags[e] = new Array } To my knowledge,the production script is just the compressed script of development environment, but why the definition of the function have been changed? And at the same time why this function does not work in production? |
rails ajax-datatables-rails empty table Posted: 09 Jul 2016 08:13 PM PDT Im kinda new to web development so sorry if I'm missing something obvious, usually I dig until I find an answer but this time I had no luck. I'm trying to integrate ajax-datatables-rails with Rails 4.2.6 and bootstrap 3 but when I load the page I get an empty table, I was following the tutorials but I don't seem to find something more recent than the rails cast or something that clues me where I'm wrong. view (index.html.erb) <table id="paciente-table" data-source="<%= pacientes_path(format: :json) %>"> <thead> <tr> <th>Paterno</th> <th>Materno</th> <th>Nombre</th> <th colspan="3"></th> </tr> </thead> <tbody> </tbody> </table> pacientes_datatables.rb include AjaxDatatablesRails::Extensions::Kaminari class PacientesDatatable < AjaxDatatablesRails::Base def initialize(view) @view = view end def sortable_columns # Declare strings in this format: ModelName.column_name @sortable_columns ||= %w('paciente.nombre', 'paciente.paterno', 'paciente.materno') end def searchable_columns # Declare strings in this format: ModelName.column_name @searchable_columns ||= %w('paciente.nombre', 'paciente.paterno', 'paciente.materno') end private def data records.map do |record| [ record.nombre, record.paterno, record.materno ] end end def get_raw_records Paciente.all end # ==== Insert 'presenter'-like methods below if necessary end pacientes_controller.rb def index respond_to do |format| format.html format.json { render json: PacientesDatatable.new(view_context) } end end pacientes.js.coffeescript $ -> $('#paciente-table').dataTable processing: false serverSide: true ajax: $('#paciente-table').data('source') pagingType: 'full_numbers' I followed the ajax-datatables-rails tutorials on setting up with a mysql db |
No comments:
Post a Comment