How to restrict order creation Posted: 27 Jun 2016 08:11 AM PDT So in my rails app I have store with products, order_items, orders, user, cart... Right now, orders are being created and saved in database upon new session for a user. So if user adds 1 order_item to his order, logs out, comes back again and ads a new order_item, new order is being created in database. The old order for that 1 order_item still exist in database however it's not being showed for a current_user on the frontend, because new order is created. What I want to achieve is that there should be only one order per 30 days per user. So even if user adds some order_items, logs out, come back again, to have that existing order associated with that user as well on the frontend. And it should be like that for 30 days... Counter for new order should start upon addition of the first order_item. To sum up: So I want not to create new orders upon new session for current_user, instead to show the order that has be created from previous session and keep it like that for 30 days... How can I achieve this? class OrderItemsController < ApplicationController def create now = Date.today if current_user.begin_date && ((now - 30) < current_user.begin_date) if current_user.order_counter >= 3 redirect_to root_path else current_user.order_counter += 1 current_user.save end else current_user.order_counter = 1 current_user.begin_date = now current_user.save end @order = current_order @order_item = @order.order_items.new(order_item_params) @order.user_id = current_user.id @order.save session[:order_id] = @order.id respond_to do |format| format.js { flash[:notice] = "ORDER HAS BEEN CREATED." } end end private def order_item_params params.require(:order_item).permit(:quantity, :product_id, :user_id) end end order_item.rb class OrderItem < ActiveRecord::Base belongs_to :product belongs_to :order validates_associated :order validates :quantity, presence: true, numericality: { only_integer: true, greater_than: 0 } validate :product_present validate :order_present before_save :finalize def unit_price if persisted? self[:unit_price] else product.price end end def total_price unit_price * quantity end private def product_present if product.nil? errors.add(:product, "is not valid or is not active.") end end def order_present if order.nil? errors.add(:order, "is not a valid order.") end end def finalize self[:unit_price] = unit_price self[:total_price] = quantity * self[:unit_price] end end order.rb class Order < ActiveRecord::Base belongs_to :order_status belongs_to :user has_many :order_items validates_length_of :order_items, maximum: 3 before_create :set_order_status before_save :update_subtotal def subtotal order_items.collect { |oi| oi.valid? ? (oi.quantity * oi.unit_price) : 0 }.sum end private def set_order_status self.order_status_id = 1 end def update_subtotal self[:subtotal] = subtotal end end cart_controller.rb class CartsController < ApplicationController def show @order_items = current_order.order_items end end |
Bundler is using a binstub that was created for a different gem - in the context of a Rails engine Posted: 27 Jun 2016 08:03 AM PDT I have created a simple Rails engine, using Rails v4.2.6 . Now it ran into problems related to the "binstub management": When I invoke the rails binary/binstub, e.g. via rails -v or when I navigate to the dummy application within spec/dummy and I want to start a rails console , I get the following warning: Bundler is using a binstub that was created for a different gem. This is deprecated, in future versions you may need to `bundle binstub my-sample-engine` to work around a system/bundle conflict. And if I use my engine within another Rails application, this error message is propagated to the hosting application - I get the same message when starting a rails console session there. The warning remains even when I invoke the console via bundle exec rails c . I found some suggestions in the answers of this Stackoverflow discussion but unfortunately the suggestions did not resolve the problem in my situation. What I have tried so far: Deleting the "top-level binstub" located in bin/ . There ony was a single binstub for rails. But, no success. If I run "rails -v" afterwards the warning appears again Deleting/re-creating the binstubs within the dummy application via rm -rf bin/ && rake rails:update:bin was not successful, too. Configuring bundler to turn off its binstub generator by bundle config --delete bin and repeating 1 and 2 did not help, too. What went wrong in my case? How can I fix the "wrong" binstub situation? Hopefully useful trivia: I'm using bundler version 1.11.2 , rails version 4.2.6 and as stated above, everything happens within a mountable engine. |
Override javascript_tag type for json-ld in Rails 3.2.x Posted: 27 Jun 2016 07:52 AM PDT Looking at the underlying code for javascript_tag it may not be possible, but does anyone know if it's possible to override the javascript_tag default type of type="text/javascript" in Rails 3.2.2? Or possible without a lot of janky code? I'm trying to do something like this, but I can look into other options. javascript_tag type: 'application/ld+json' do some stuff here end |
Ruby-on-Rails: Can enum value be a string. Where is this documented? Posted: 27 Jun 2016 07:49 AM PDT Can someone point me to some ROR documentation that describes setting the value of an enum as a string? All the documentation and examples I've found seem to indicate that the value should be an integer. However I am able to create an enum with string values, use it in view and save it to the database without any issues. I would really like to find out more on this topic. Example that works Set in ModelName enum category_enum: { 'abc efg'=> 'alpha', 'hot dog' => 'bun' } Set in view <%= f.select :category, ModelName.category_enums %> |
Rails. Search MongoDB field that is an array of arrays Posted: 27 Jun 2016 07:49 AM PDT I'm writing my own RoR based archive app for email and have a field named headers which is an array of arrays. The first element of each sub-array is the header name and the second is the header value. I'd like to be able to search for headers of certain types, i.e.."Received', 'X-Spam-Status', etc. and/or the contents of a header, i.e. 'from mail.apache.org', 'score=-4.7', etc. I've tried .where(headers: {'$in' => [['Received']]}) and many variations with no luck. Can anyone help me out? Thx. in advance. |
How to add and remove a class to hide and show a table row? Posted: 27 Jun 2016 07:46 AM PDT In my current situation in my Ruby on Rails application, I am trying to make a drop-down function on each table tow to show advanced details for a server that comes from a database. My through process is to make the hidden row default to display: none; then add a viewing class when it is clicked to view it, then hide it when it is clicked again. Here is my javascript: var hideDetails, showDetails; showDetails = function() { $(this).closest('tbody').addClass('viewing'); return false; }; hideDetails = function() { $(this).closest('tbody').removeClass('viewing'); return false; }; $table.on('click', 'tbody.viewing', hideDetails); $table.on('click', '.details-link', showDetails); Then my css: table.collapsible { // css for drop-down #hiddenRow.details { display: none; tbody.viewing { #hiddenRow.details { display: table-row; } } } } Lastly, my HTML code: <table id="servertable" class="paginated table collapsible table-hover sortable" data-sort-name="name" data-sort-order="desc"> <tr style="background-color: #cccccc"> <th><%= sortable "pod_id" %></th> <th><%= sortable "ip"%></th> <th><%= sortable "status"%></th> <th><%= sortable "datacenter"%></th> <th><%= sortable "memory_used"%></th> <th></th> </tr> <!--A for loop to iterate through the database and put it into the table--> <tbody> <% @servers.each_with_index do |server| %> <tr> <td><%= server.pod_id %></td> <td><%= server.ip %></td> <td><%= server.status %></td> <td><%= server.datacenter %></td> <td><%= (server.memory_used * 100).floor %>%</td> <td><input type="button" onclick="showDetails(); hideDetails();"></input></td> <tr id="hiddenRow"> <td colspan="6">Information</td> </tr> </tr> <% end %> </tbody> </table> My problem is that even though in my css, I have the default display of the hidden row to be none, it is still showing up on the screen. As well as the button not functioning as well. Some help would be appreciated. Note: There is some extra stuff in my HTML code because I have some other functions for my table such us sortable columns, just ignore that, it doesn't have to do with my question. |
Having a Ruby on Rails Selector without a form Posted: 27 Jun 2016 07:42 AM PDT I have a schools' program table set up, and want a user to be able to add a new program to a school. The new school program path requires a school passed to it to denote which school is getting a new program. In the first scenario, there is already a school selected and so a new program can be added to that school. In the second scenario however, there is no school selected yet. I was wondering how to add a dropdown that has all of the schools available so that someone can choose which school they want to add a program in - but I am trying to do so without a form. <% if @school %> <% if can? :create, @program %> <%= link_to 'New Program', new_school_program_path(@school), class: 'btn btn-primary' %> <br/> <% end %> <% else %> <% if can? :create, @program %> <%= select @selected_school, [School.all]%> <%= link_to 'New Program', new_school_program_path(@selected_school), class: 'btn btn- primary' %> <br/> <% end %> <% end %> |
Prevent Google crawling other folders in /var/www/ Posted: 27 Jun 2016 07:57 AM PDT We have a website build on Ruby on Rails reverse proxied with Apache. So the root folder for the website would be /var/www/html/digiryte and the folder structure is similar to this /var/www/html/ rails_website/ folder1/ folder2/ index.html The trouble is google's webmaster console is showing crawl errors with the url like /html/rails_website/public/assets/... How is this possible? How can I stop google from indexing those folders? |
Rails application to not redirect to HTTPS on specific controller and action Posted: 27 Jun 2016 07:43 AM PDT How can my application not redirect to HTTPS on a certain controller and action ? In my case it's the controller transaction and action update_payment . I'm having loop redirect problem on production. I've tried using the the gem rack-ssl-enforcer and putting the following in the production.rb : config.middleware.use Rack::SslEnforcer, :except => [%r{update_payment$}], :strict => true Still, it seems it's not working.. |
rake aborted! cannot load such file Ruby on Rails Posted: 27 Jun 2016 07:32 AM PDT I am trying to run a ruby file that updates the database using the rake task . But overtime I run the code, I get an error saying : rake aborted! cannot load such file -- app/services/insert_data The ruby file 'insert_data' is located under the app directory in a folder named 'services' Here is the rake task I created to run it: require 'app/services/insert_data' namespace :record_generate do task :test do ruby "app/services/insert_data" end end Please help in removing this error. |
Ruby Retrieving from Array Posted: 27 Jun 2016 07:22 AM PDT So i get an array of hashes like this [1, {"item_name"=>"Estella Top", "item_number"=>"73", "quantity"=>"1", "option_name1_"=>"UK - 4, White"}] [2, {"item_name"=>"Test Top", "item_number"=>"74", "quantity"=>"1", "option_name1_"=>"UK - 4, Red"}] I have this create action: def create f_turn = extract_items Page.create!(line_item_id: "#{f_turn.fetch("item_number")}", option_name: "#{f_turn.fetch("option_name1_")}", quantity: "#{f_turn.fetch("quantity")}") render nothing: true end extract items is a function that extracts the array. I need those values, but for some reason, its not working. I've also tried: def create f_turn = extract_items f_turn.each do |key, values| Page.create!(line_item_id: ["item_number"], option_name: ["option_name1_"], quantity: "["quantity"]) render nothing: true end None of them work. With the latter, instead of the actual value, i get "[\"item_number\"]" as the value. Any help would be appreciated! Thanks in advance! UPDATE Mistakes in the code def extract_items mod_params = Hash.new{|k, v| k[v] = {} } ITEM_PARAM_PREFIXES.each do |item_data_key| key_tracker = 1 loop do current_key = (item_data_key + key_tracker.to_s).to_sym if params.include? current_key mod_params[key_tracker][item_data_key] = params[current_key] else break end key_tracker += 1 end end mod_params end |
Using database entries to populate checkbox data ruby rails Posted: 27 Jun 2016 07:06 AM PDT I'm trying to create a page with a series of checkboxes on it for which the text associated with them will be pulled from a database. The view on which the form should be is named keyword_search and is located within the searches folder. The below is the code I've used to try and create the checkboxes in the view: <% @topic.each do |degree| %> <form action="recommender_results.html.erb" method="get"> <input type="checkbox" name="topic" value="topic"><%= recommend.topic %><br> </form> And below is the code I have within the searches contrller: def new @topic = Recommend.new end def keyword_search @topic = Recommend.all.select(:topic) end |
Can I Populate / update a new record after using find_or_initialize_by with one line like when using new()? Posted: 27 Jun 2016 07:41 AM PDT I am in the process of changing some functionality and as such, I want to use find_or_initialize_by to replace new My modal has 13 columns modal = Modal.new(col1: col1, col2: col2..... col13: col13) The new code is: modal = Modal.find_or_initialize_by(col1: col1, col3: col3) and now I need to either populate or update the remaining 11 columns. Can this be done on one line? I would rather not write: modal.col1 = col1 modal.col2 = col2 .... modal.col13 = col13 Thanks |
Multiple urls with Paperclip Posted: 27 Jun 2016 06:59 AM PDT Is it possible to upload multiple files with Paperclip? I've tried my best by going through their docs but noting useful. I want to submit an array value to a rails 5 controller using react. My state has an array, let's say [a, b, c] . In my render, I have: <form> <!-- I have an input file button for the upload visible --> <input type="hidden" name="user[image][]" value={this.state.files} /> </form> To make this example slimmer, I only show the hidden field where the value is. The submitted params looks "encrypted" but I'm confident I see the array. My controller: # :image is not permitted params[:user][:image].each do |image | User.find(1).update_attributes(user_params.merge({image: image})) end Only the first image in the array is being saved. Does paperclip supports multiple? The aim is: User.find(1).image.url , then I'd see an array of urls. I'm using PostgreSQL as the db so not sure if I should make the table column an array but do paperclip supports that? |
How do I express i18n and devise on route.rb Posted: 27 Jun 2016 06:46 AM PDT I'm configuring omniauth and devise with i18n on route.rb But I can't figure out how. scope "(:locale)", locale: /en|ja/ do get '/' => 'frontpage#index' get 'restaurant/' => 'restaurant#index' get 'restaurant/:id' => 'restaurant#show' get 'menu/' => 'menu#index' get 'menu/:id' => 'menu#show' get 'area/' => 'area#index' get 'area/:id' => 'area#show' devise_for :users, :controllers => { :sessions => "users/sessions", :registrations => "users/registrations", :passwords => "users/passwords", :omniauth_callbacks => "users/omniauth_callbacks" } end Does it make sense? And could you tell me how to configure please? |
capybara have_title NoMethodError Posted: 27 Jun 2016 06:52 AM PDT At the moment, this is a simple project - just a couple of static pages. I'm developing a generic test framework but am struggling to differentiate between the different test options. I have added Rspec, Capybara, Faker, Factory Girl, Spring, and shoulda (though I'm not using the shoulda matchers at the moment). I have this controller test file: require 'rails_helper' RSpec.describe StaticPagesController, type: :controller do describe "GET #a_page" do before(:each) { get :a_page } it "returns http success" do expect(response).to have_http_status(:success) end it "has a page title Static Site" do expect(response).to have_title('Static Site') end end end When this runs through guard, it throws an error stack: 23:13:39 - INFO - Run all 23:13:39 - INFO - Running all specs Running via Spring preloader in process 4498 Running via Spring preloader in process 4506 /home/steve/workspaces/static_site/db/schema.rb doesn't exist yet. Run `rake db:migrate` to create it, then try again. If you do not intend to use a database, you should instead alter /home/steve/workspaces/static_site/config/application.rb to limit the frameworks that will be loaded. .F Failures: 1) StaticPagesController GET #a_page has a page title Static Site Failure/Error: expect(response).to have_title('Static Site') NoMethodError: undefined method `match' for nil:NilClass Did you mean? catch # /home/steve/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/queries/title_query.rb:18:in `resolves_for?' # /home/steve/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/node/document_matchers.rb:20:in `block in assert_title' # /home/steve/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/node/simple.rb:144:in `synchronize' # /home/steve/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/node/document_matchers.rb:19:in `assert_title' # /home/steve/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/rspec/matchers.rb:105:in `matches?' # ./spec/controllers/static_pages_controller_spec.rb:34:in `block (3 levels) in <top (required)>' # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-commands-rspec-1.0.4/lib/spring/commands/rspec.rb:18:in `call' # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/command_wrapper.rb:38:in `call' # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:191:in `block in serve' # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:161:in `fork' # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:161:in `serve' # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:131:in `block in run' # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:125:in `loop' # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application.rb:125:in `run' # /home/steve/.rvm/gems/ruby-2.3.1/gems/spring-1.7.1/lib/spring/application/boot.rb:19:in `<top (required)>' # -e:1:in `<main>' Finished in 0.029 seconds (files took 2.54 seconds to load) 2 examples, 1 failure Failed examples: rspec ./spec/controllers/static_pages_controller_spec.rb:33 # StaticPagesController GET #a_page has a page title Static Site The first test runs OK and, without the second, I get a clean result. I've spent a lot of time going over my config and it looks OK. I have also looked at the docs and some support sites. Can anybody help out? |
Using images from database with embedded ruby in bootstrap carousel Posted: 27 Jun 2016 06:35 AM PDT My carousel works with this: <div class="item"> <a href="https://www.google.com" target="_blank"> <%= image_tag "happyface.jpg", class: "imgslide" %> <div class="carousel-caption"> <p>Eating an apple a day keeps the doctors away </p> </div> </a> </div> But does not work when I attempt this: <div class="item"> <%= link_to(@articles.first.source, target: "_blank") do %> <%= image_tag(@articles.first.artwork.url, class: "imgslide") %> <div class="carousel-caption"> <%= @articles.first.title %> </div> <% end %> </div> How do I make this work? |
How to Retrieve or Change the msql password for Ruby on Rails Posted: 27 Jun 2016 07:09 AM PDT I am doing my very first practice on ruby on rails and everything was going fine until I tried running the server for the first time. On the command line (while in the root directory of my proyect) I typed "rails server" and when visiting localhost:3000 in the browser I get this error message: "Mysql2::Error Access denied for user 'root'@'localhost' (using password: YES)" Per the instructions it says that I must comment out the "#database: simpe_cms_development" in the database.yml which I did. It also says that I must provide the password that I set when installing msql. I set the password in database.yml file as "boots" username: root password: boots host: localhost But I still get the same error. My problem is that I am not sure now if this is the correct password I set to begin with. What I want to know is how to retrieve that original password I set o how to set a new one. Thanks! PS: I've just opened up mysql command line client and the first thing it ask for is a password to allow access. I Typed "boots" and it did allow access to the mysql command line client. So the problem I have is NOT the pássword. :( Any Ideas on how to debug anybody? |
How to catch base exception class in Ruby on Rails? Posted: 27 Jun 2016 06:01 AM PDT I'd like to catch any RoR exceptions in REST API application with 'rescue_from'. rescue_from StandardError do |exception| message = Rails.env.production? ? 'API server error' : exception.message render json: {status: "Error", message: message}, status: :internal_server_error end but it catches too much irrelevant exceptions. Can I catch RoR exceptions only? Is it a good practice at all? If not, what else you can recommend? |
How to display a pie chart of all service->orders->count? Posted: 27 Jun 2016 06:00 AM PDT I am trying to display a pie chart displaying all the count of services by using chartkick gem : http://chartkick.com/ service has_many :orders orders belongs_to :service My db schema is here create_table "services", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "priority" t.text "description" t.integer "delivery_charges" t.integer "min_stamp" end create_table "orders", force: :cascade do |t| t.integer "document_id" t.integer "user_id" t.integer "status_id" t.string "stamp_amount" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "service_id" t.string "total_amount" t.string "delivery_amount" t.string "txnid" t.string "invoice_url" t.boolean "draft_confirmed", default: false t.string "soft_copy_url" t.boolean "draft_required", default: true t.integer "delivery_status_id" t.integer "delivery_partner_id" t.string "delivery_tracking_no" t.string "product" t.integer "platform_id", default: 1 t.integer "address_id" t.string "pickup_amount" t.boolean "draft_created", default: false t.string "draft_url" t.text "correction" t.integer "coupon_id" t.string "discount" t.text "summary", default: "" end There are several services such as affidavit, notary etc. Each service in turn have one or more document orders of type "house agreement", "bonds" etc. I want to display the order count of these different documents of each service in a pie chart. How do I achieve this. Please help. Let me know if more data is required. |
Rails - how to fetch from ActiveRecord object only specific records? Posted: 27 Jun 2016 06:21 AM PDT I get this from an ActiveRecord call: #<ActiveRecord::Associations::CollectionProxy [ #<CarService id: nil, car_id: nil, car_service: 1, created_at: nil, updated_at: nil, car_type: 0>, #<CarService id: nil, car_id: nil, car_service: 11, created_at: nil, updated_at: nil, car_type: 1>]> Once I get this, I need to filter only records where car_type = "0" . How to do that without doing another database call (WHERE car_type = "0" )? Thank you in advance. EDIT: this: car.car_services.select{|key, hash| hash['car_type'] == "1" } does not work. |
rake aborted! NoMethodError: undefined method when migrated to Rails 4.0 Posted: 27 Jun 2016 06:51 AM PDT I am working on Rails application migration from 3.2.13 to 4.0.0, before running the application, I need to run a seed file: seeds.rb # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }]) # Mayor.create(:name => 'Daley', :city => cities.first) # Create subscription plans SubscriptionPlan.find_or_create_by_name(name: "free", amount: 0.00, renewal_period: 1, trial_period: 30, description: 'Free Plan') SubscriptionPlan.find_or_create_by_name(name: "year", amount: 149.00, renewal_period: 12, trial_period: 30, description: "Year Plan") This is the table: create_table "subscription_plans", :force => true do |t| t.string "name" t.decimal "amount", :precision => 10, :scale => 2 t.integer "renewal_period", :default => 1 t.integer "trial_period", :default => 1 t.text "description" end While running rake db:seed, this is the error I am getting an error in current version where it is fine in previous version. Error: rake aborted! NoMethodError: undefined method `trial_interval' for Did you mean? trial_period /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/attribute_methods.rb:436:in method_missing' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/attribute_methods.rb:131:in method_missing' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validator.rb:151:in block in validate' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validator.rb:150:in each' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validator.rb:150:in validate' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:283:in _callback_before_39' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:407:in _run__3876620741187521333__validate__callbacks' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:80:in run_callbacks' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validations.rb:373:in run_validations!' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validations/callbacks.rb:106:in block in run_validations!' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:373:in _run__3876620741187521333__validation__callbacks' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/callbacks.rb:80:in run_callbacks' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validations/callbacks.rb:106:in run_validations!' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activemodel-4.0.0/lib/active_model/validations.rb:314:in valid?' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/validations.rb:70:in valid?' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/validations.rb:77:in perform_validations' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/validations.rb:51:in save' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/attribute_methods/dirty.rb:32:in save' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:270:in block (2 levels) in save' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:326:in block in with_transaction_returning_status' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:202:in block in transaction' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:210:in within_new_transaction' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:202:in transaction' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:209:in transaction' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:323:in with_transaction_returning_status' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:270:in block in save' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:281:in rollback_active_record_state!' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/transactions.rb:269:in save' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/protected_attributes-1.0.3/lib/active_record/mass_assignment_security/persistence.rb:46:in create' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/relation.rb:121:in block in create' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/relation.rb:270:in scoping' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/relation.rb:121:in create' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-deprecated_finders-1.0.4/lib/active_record/deprecated_finders/dynamic_matchers.rb:141:in dispatch' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/dynamic_matchers.rb:67:in find_or_create_by_name' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/dynamic_matchers.rb:20:in method_missing' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/attr_encrypted-1.2.1/lib/attr_encrypted/adapters/active_record.rb:50:in method_missing_with_attr_encrypted' /home/abc/Desktop/Proj2/db/seeds.rb:10:in <top (required)>' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in load' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in block in load' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:213:in load_dependency' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:222:in load' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/railties-4.0.0/lib/rails/engine.rb:540:in load_seed' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/tasks/database_tasks.rb:153:in load_seed' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/activerecord-4.0.0/lib/active_record/railties/databases.rake:181:in block (2 levels) in ' /home/abc/.rvm/gems/ruby-2.3.0@proj/gems/rake-11.2.2/exe/rake:27:in <top (required)>' /home/abc/.rvm/gems/ruby-2.3.0@proj/bin/ruby_executable_hooks:15:in eval' /home/abc/.rvm/gems/ruby-2.3.0@proj/bin/ruby_executable_hooks:15:in `' Tasks: TOP => db:seed (See full trace by running task with --trace) I don't know where this trial_interval came from. I have searched entire application. Please help me. |
Rails rspec undefined method `receive_message' for #<RSpec::ExampleGroups:: Posted: 27 Jun 2016 05:48 AM PDT I'm trying to mock some data inside before(:each) and get NoMethodError: undefined method `receive_message' for #<RSpec::ExampleGroups::CurrencyExchange:0x007f87c652f3c8> my before(:each before(:each) do @rates = {"exchangerates"=> {"row"=> [{"exchangerate"=>{"ccy"=>"EUR", "base_ccy"=>"UAH", "buy"=>"28.33917", "sale"=>"28.33917"}}, {"exchangerate"=>{"ccy"=>"RUR", "base_ccy"=>"UAH", "buy"=>"0.38685", "sale"=>"0.38685"}}, {"exchangerate"=>{"ccy"=>"USD", "base_ccy"=>"UAH", "buy"=>"24.88293", "sale"=>"24.88293"}}, {"exchangerate"=>{"ccy"=>"BTC", "base_ccy"=>"USD", "buy"=>"605.3695", "sale"=>"669.0926"}}]}} obj = double() @request = allow(obj).to receive_message(@rates) end How to fix it? |
Apache configuration to access files from outside of ruby Posted: 27 Jun 2016 05:32 AM PDT My server configuration is as follows: Server running apache2 Passenger is providing ruby application I have an images folder which is outside the ruby app The ruby application has the following path: /home/myuser/domains/domainname/rubyapp The images folder lies at /home/myuser/images I added a Location and an Alias into my apache2 configuration <Location /home/myuser/images> PassengerEnabled off allow from all Require all granted Options -Indexes +IncludesNOEXEC +SymLinksIfOwnerMatch +ExecCGI </Location> Alias /images /home/myuser/images I start the ruby application with: passenger start -p 3001 -d -e production Inside the images folder there is an image file asd.jpg - which i cannot display, because i get a ruby 404 error message. I want to access the image with www.mydomain.com/images/asd.jpg What am i doing wrong? Which configuration has to be edited (and how)? |
How to skip the malformated & invalid utf-8 errors.When csv file uploading in ralis app? Posted: 27 Jun 2016 05:30 AM PDT I have handle more-then 5lks data.I have working with CSV & XLSX formats. When i uploading a CSV file i have ('Rails Import CSV Error: invalid byte sequence in UTF-8' and 'Malformed error') and-then i uploading a Xlsx file i have ('Roo spreadsheet uploading OLE2 signature is invalid'). Please someone help me? This my view page code... <%=form_for[@product],:url{:controller=>"products",:action=>"import_process"} do |f| %> <%= f.file_field :file1,:accept=>".csv"%> <button type="submit" class="btn btn-info" onclick="return ValidateExtension()" data-qslid="l2"><i class="fa fa-cloud-upload"></i>Upload</button><br/><br/> <%end%> |
Getting id errors when trying to delete tags Posted: 27 Jun 2016 05:34 AM PDT I am extremely new to ruby on rails and I was following a tutorial to set up a simple blog style website. I had implemented tags on the articles but now I'm getting errors when trying to implement the deleting of tags. I think this is where the error is coming from. def destroy @tag = Tag.find(params[:id]) @tag.destroy flash.notice = "Tag '#{@tag.name}' Deleted!" redirect_to action: "index" end I think it's the line @tag = Tag.find(params[:id]) that's causing the following error: Couldn't find Tag with 'id'=#< Tag::ActiveRecord_Relation:0x007fdd2c016ba0> I'm stuck with this because I managed to implement the deleting of articles in this way so I'm unsure as to why this won't work. Edit: This is the view file. <h1>All Tags</h1> <ul id="tags"> <% @tag.each do |tag| %> <li> <%= link_to tag.name, tag_path(tag) %> <%= link_to "delete", tag_path(@tag), method: :delete, data: {confirm: "Really delete the tag?"} %> </li> <% end %> </ul> |
Rails: Update data via link_to (without view) Posted: 27 Jun 2016 06:19 AM PDT I'd like to update the data without form. Although there are similar questions, they don't work for me. Update field through link_to in Rails link_to update (without form) What I'd like to do is to delete data as followings; For example, delete name and address when delete link is clicked. id | name | address | ... 12 | aaa | bbb | ... to id | name | address | ... 12 | | | ... Although I tried some, error was displayed.(such as ActionController::RoutingError ) schema create_table "rooms", force: :cascade do |t| t.string "name" t.text "address" ... model schedule.rb class Schedule < ActiveRecord::Base belongs_to :user has_many :rooms, inverse_of: :schedule, dependent: :destroy accepts_nested_attributes_for :rooms, allow_destroy: true ... room.rb class Room < ActiveRecord::Base belongs_to :schedule, inverse_of: :rooms default_scope -> { order(day: :asc) } ... view I'd like to add the link in schedules/_schedule.html.erb It has the followings; ... <% schedule.rooms.each do |room| %> ... <% if room.name.present? %> <%= link_to "Delete", rooms_path(room, room:{address: nil}) , method: :put, data: { confirm: "You sure?"} %> ... I also tried another code as below, but they don't work. <%= link_to "Delete", rooms_path(room:{address: nil}) , method: :put, data: { confirm: "You sure?"} %> <%= link_to "Delete", rooms_path(room) , method: :put, params: {address: nil}, data: { confirm: "You sure?"} %> and so on. routes.rb ... resources :schedules do resources :events end resources :schedules do resources :rooms end resources :rooms do resources :events end ... It would be appreciated if you could give me any suggestion. |
Populate dropdown menu from csv file rails Posted: 27 Jun 2016 05:21 AM PDT How can you populate a drop down menu with values from a CSV file in rails 4? Can you provide an example? |
Rails 4 - notifyor gem is not sending any notifications Posted: 27 Jun 2016 05:10 AM PDT In rails 4, I have used gem 'notifyor' for sending desktop notifications. Referred by https://github.com/ndea/notifyor. Issue is notifications are not sending and there are no errors also. In model, I have tried with below methods separately, notifyor only: [:update] and notifyor messages: { update: -> (model) { "My Message for model #{model.id}." } } Parallel I am running redis-server . After updating the value there is no notification is sending. Please help me to solve this issue. How to run notify_me --ssh-host some_host --ssh-port some_port --ssh-user some_user command(please explain briefly) if it necessary to use? |
Adding a counter to controller. Rails 4 Posted: 27 Jun 2016 05:33 AM PDT I have a rails 4 app. In the controller, I iterate through each assignment entry in the database to check if a requirement is associated with more than one assignment. However, I can't figure out how to add a counter, i.e. hit = 0, hit = 1, etc. to the controller. EDIT: The relationship between assignment and requirement is HABTM. My code is below: def check_requirements @assignments = Assignment.all @assignment = Assignment.find(params[:id]) @requirement = Requirement.find(params[:requirement_id]) @assignments.each do |assignment| if assignment.include(requirement) #here's where the counter should go end end if counter is greater than zero or one, do nothing else @assignment.delete(requirement) end |
No comments:
Post a Comment