w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » RUBY ON RAILS » Page 10
Active Record Association?
I suspect you're having trouble because you are defining two belongs_to for the same symbol. Try doing this instead: class Note < ActiveRecord::Base belongs_to :user, foreign_key: 'user_id', class_name: 'User' belongs_to :recipient, foreign_key: 'recipient_id', class_name: 'User' end Then try calling note.recipient

Categories : Ruby On Rails

Form_helper and routing
@movie did not persisted for some reason so that redirect_to hasn't been performed. Add else statement to condition: if @movie.save redirect_to movies_path(@movie) else render action: 'new' end

Categories : Ruby On Rails

Escaping A String Within an Escaped String?
Remember that you can avoid escaping by using single quotes: "#{@model.name}" # => "Test" '#{@model.name}' # => "#{@model.name}" So if you're intending to defer evaluation for one round, you should just escape like that or make it a more literal version: "#{@#{class_name}.name}" That can be evaluated twice, though I'm not sure that it'll work exactly as planned in the generator system.

Categories : Ruby On Rails

duplicate records when destroying associated models during update
Thank @blelump, you're right. It worked when my params was made as such: "main_slot"=> { ... "citizenship_requirements_attributes"=> [{"citizenship_id"=>"1", "id"=>"6033", "_destroy"=>"false"}, {"citizenship_id"=>"2", "id"=>"6034", "_destroy"=>"false"}, {"citizenship_id"=>"3", "id"=>"6035", "_destroy"=>"true"}, {"citizenship_id"=>"4", "id"=&g

Categories : Ruby On Rails

How to measure background activerecord model performance in rails?
I think best tool here would be ruby-prof. It can show the overall time spent in each method. In addition, it will also show which methods call the current method and which methods its calls. Here is example output with comments.

Categories : Ruby On Rails

How can i make a query that returns the top 10 users with most activities done?
It looks like you can add a counter to the Activity class: class Activity < ActiveRecord::Base has_one :sport belongs_to :account, :counter_cache => true has_one :place ... then add a column to your Account table called activities_count where you can then call: Account.find(:all, :order => 'activities_count', :limit => 10) I used this answer to help (there is also anothe

Categories : Ruby On Rails

ArgumentError: Invalid route name, already in use: 'root' due to rails routes getting initialized twice
The issue was because routes.rb was called twice. Once during application init in application.rb and then I manually required a initializer at the end of application.rb which was causing the app to be initialized twice.

Categories : Ruby On Rails

script/plugin install for rails 4 (daemon generator)
Rails::Plugin is deprecated and has been removed since Rails 4.0. Instead of adding plugins to vendor/plugins use gems or bundler with path or git dependencies. Also if your goal is to run logic in the background there are way newer options to implement like Resque https://github.com/resque/resque or Sidekick https://github.com/mperham/sidekiq

Categories : Ruby On Rails

Unable to start rails in ubuntu
Read the Rails guide Starting up the Web Server :- Compiling CoffeeScript and JavaScript asset compression requires you have a JavaScript runtime available on your system, in the absence of a runtime you will see an execjs error during asset compilation. Usually Mac OS X and Windows come with a JavaScript runtime installed. Rails adds the therubyracer gem to the generated Gemfile in a commente

Categories : Ruby On Rails

Rails - override a setter for an active record attribute
I think it's ok to have separate method for this. However, if you want patch update_attributes you can write like this: def update_attributes(attrs) update_location = attrs.delete(:update_location) super.tap { notify if update_location } end Or you can use custom attr & callback: after_update :notify, if: :need_notify attr_accessor :need_notify # then user.update_attributes location:

Categories : Ruby On Rails

Problems using options_for_select helper in rails
You're using f.label so probably you also would like to use f.select instead select_tag. The main difference between them is that select_tag(:activityType, options_for_select([[]]) ) gives exactly activityType param name, so it's accessible in controller via params[:activityType], whereas: f.select(:activityType, options_for_select([[]]) ) gives params[:object_name][:activityType]. So that,

Categories : Ruby On Rails

Does heavy use of methods within a view hinder caching?
No, the implementation you are suggesting does not negatively impact caching - This includes page caching, action caching as well as Russian doll caching. While the cases for page caching or action caching are fairly obvious, the reason Russian doll caching is also unaffected by custom view builders is because if the cache_key of model does not change - the block passed to the cache helper does n

Categories : Ruby On Rails

How to add upload feature and show upload file in rails using AWS S3?
You can use paper_clip gem which supports S3 upload and download. Check this https://devcenter.heroku.com/articles/paperclip-s3

Categories : Ruby On Rails

Bower and Asset Precompilation in Rails
You can explicitly define what you want to precompile in config/initializers/assets.rb: Rails.application.config.assets.precompile += %w(dist/*) By default it precompiles application.js and application.css and some other stuff, you can override this behavior if you do not want them to be precompiled. Take a look at Rails official guide, it explains how to use more difficult rules of including

Categories : Ruby On Rails

Rails4 - How to add reference to an existing table?
You are correct, there are no differences, just make sure you name the migration with the correct table name, for example, add a movement reference to table invoices: rails g migration AddMovementRefToInvoices movement:reference

Categories : Ruby On Rails

installing rails with gem , error loading command : install undefined method 'invoke_with_build_args`
You need to install the zlib development headers. Refer to your OS's package manager instructions on how to do this. On a RedHat derivative it would look something like this: sudo yum install zlib-devel For ubuntu: sudo apt-get install zlib1g-dev Hope this helps

Categories : Ruby On Rails

Rails 4 : Access to association child model
First, you need to complete your associations: Every belongs_to should have a corresponding has_many/has_one class Category has_many :articles end class Article has_many :comments belongs_to :category end class Comment has_many :votes, class_name: :votes #rails will look for class Vote, so you have to specify that the class name is actually 'votes' belongs_to :article end Then w

Categories : Ruby On Rails

Ruby on Rails - Activerecord::Associations method error
@recipes = Recipe.all returns associations you should do something like this <%- @recipes.each do |recipe| %> <p> <strong>Title:</strong> <%= recipe.title %> </p> <p> <strong>Content:</strong> <%= recipe.content %> </p> <p> <strong>Duration:</strong> <%= recipe.duration %> </p> <p>

Categories : Ruby On Rails

Rails: What is the correct way of saving the time of a video?
The way of keeping time depends of you business logic. I would prefer to keep length in seconds, and then convert to minutes, hours and so on. You can easily do it by simple devision: minutes = (seconds / 60) seconds_left = (seconds % 40) human_time = "#{minutes}:#{seconds_left}"

Categories : Ruby On Rails

data retrieval between two DateTime object with equal intervals Rails
Provided that seconds of accuracy is sufficient you can compare two DateTime objects by simple subtraction: a = DateTime.new(2014) # Wed, 01 Jan 2014 00:00:00 +0000 b = DateTime.new(2015) # Thu, 01 Jan 2015 00:00:00 +0000 diff = b.to_i - a.to_i # in seconds. puts "2014 has #{ (diff / 1.day).round } days" ActiveSupport gives us methods on which we can use to convert integers to time which makes

Categories : Ruby On Rails

Trouble installing gems with bundler
The following : In Gemfile: rails (= 3.0.1) ruby depends on bundler (~> 1.0.0) ruby means the version of bundler required is greater than or equal to 1.0.0 but strictly less than 1.1.0. Rails 3 is depending on an old version of bundler. At this point of time, you should try out Rails 4 instead :) You may read up more about the "version syntax" in http://guides.rubygems.org/pat

Categories : Ruby On Rails

Undefined method `user_id=' for #
You don't have user_id in your migration. To solve this you can follow either of these: Solution 1: Create a new migration: $ rails g migration AddUseIdToComments user_id:integer open AddUseIdToComments migration file to see if it has: add_column :comments, :user_id, :integer then run: $ rake db:migrate Solution 2: Instead of: create_table "comments", force: true do |t| t.text "

Categories : Ruby On Rails

chef solo private key missing when trying to use database cookbook
The database::master recipe is not currently compatible with chef-solo, though it could be. Either use chef-client --local or the chef-solo-search cookbook, or patch the cookbook to not use the search API.

Categories : Ruby On Rails

Can't run rails c in terminal because of "Pry failed to get user input using `Readline`."
Had this issue before, it ended up being a problem with rvm and my path while running rails/bundler commands from a particular prompt. Try rvm list and rails -v to make sure there are no errors/inconsistencies. Then bundle install and rails console should work fine. Hopefully this helps!

Categories : Ruby On Rails

Rails4+Devise: "hide" routes when user is not authenticated
A more graceful way of handling errors when a user is not signed in is adding a method to your application controller. For example display_404 In your display_404 method add raise ActionController::RoutingError.new('Not Found') When this method is called it will raise Rails' own error page and log 'Not Found' in the log file. In development this will be shown but on screen but for production i

Categories : Ruby On Rails

Rails build fails in Travis due to undefined method 'encrypted_password=' for User
Well when I created my tables in MySQL I used capital names for all my table names. For some reason when running it locally, the table names were still uppercase in development mode, but were lowercase for test mode. So, in my user model, I simply changed the self.table_name = "USERS" to self.table_name = "users" and that fixed my problem.

Categories : Ruby On Rails

Rails 4. Counter for the unique ID
There are a couple things you need to consider here: Your ids will have leading zeros so they're not numbers, they're strings that contain digit characters. You should let the database take care of the counter. Anything you try to do in Ruby will be a nasty mess of kludges and race conditions. Similarly, you should let the database take care of building the id. Using a string for the id is a b

Categories : Ruby On Rails

Issue with rufus-scheduler when we have multiple EC2 instances
Let's assume you've followed https://github.com/jmettraux/rufus-scheduler#so-rails You could modify the initializer in this way: # # config/initializers/scheduler.rb require 'rufus-scheduler' s = Rufus::Scheduler.singleton unless File.exist?(File.dirname(__FILE__) + '/../../no_scheduling') s.every '1m' do Rails.logger.info "hello, it's #{Time.now}" end end Then in the Rails root of

Categories : Ruby On Rails

How do I batch insert documents into MongoDB and only reject duplicates?
If you use an Unordered Bulk Write Operation, the entire batch will be attempted and an error report will be returned. This is using the Mongo Ruby Driver directly. I do not think that Mongoid supports this api directly. This thread describes a solution using Mongoid.

Categories : Ruby On Rails

Error with Heroku remote: /usr/bin/mate -w: /usr/bin/mate: No such file or directory
 |master| → git config -e /usr/bin/mate -w: /usr/bin/mate: No such file or directory error: There was a problem with the editor '/usr/bin/mate -w'. This command tries to open default text editor. In this context it is TextMate. But it seems that you don't have it installed. Just change your default editor and it will success

Categories : Ruby On Rails

Rails 4 ActionMailer with gmail Net::SMTPAuthenticationError: 534-5.7.14
Go to your Google Account settings, find Security -> Account permissions -> Access for less secure apps, enable this option. About this option: https://support.google.com/accounts/answer/6010255

Categories : Ruby On Rails

how to dynamic add attributes on Active Model Serializers
You can create different serializers and respond_with or render with a custom serializer like so: # serialize an array of WeatherLog(s) render json: objects, each_serializer: WeatherLogSerializer # serialize a WeatherLog render json: object, serializer: WeatherLogSimpleSerializer # just gimme id and temp class WeatherLogSimpleSerializer < ActiveModel::Serializer attributes :id, :temperatur

Categories : Ruby On Rails

How to calculate totals before_save in has_many through relations
You could not get ids in your callbacks as they are not persisted in your database yet and you want to join which will never work since no records. after_save callback will reserve an id to the record but you cannot get that unless after_commit your new data. Only persisted records have ids. you have two cases Continue with your design that BillLine and taxes are many_to_many association. Cha

Categories : Ruby On Rails

How can I use postgesql "inner join" in a ruby on rails app?
This isn't an issue with Rails nor Postgres, per se. joins is the correct method to use for an inner join (which is the default join in Postgres). The issue here is more of a pure code issue. What the error you mentioned means is that the object referred to by the symbol :event does not have a sid method defined for it, and so the NoMethodError is raised when you try to call it. Without the code

Categories : Ruby On Rails

How to add link mark as read notification rails?
Create new controller method, read_all, with contents: def read_all current_user.activities.where(read: false).update_all(read: true) end Set up a route. If you have set up read_all method inside ActivitiesController, do: resources :activities do post :read_all, on: :collection end Make a link: <%= button_to "Read all", read_all_activities_path, method: :post %>

Categories : Ruby On Rails

Define Custom Object Lifecycle Hooks In Ruby
The before/after_callback syntax is handled in ActiveModel::Callbacks through #define_model_callbacks. The raw ActiveSupport::Callbacks will require you to use #set_callback without any syntactic sugar: module Active extend ActiveSupport::Concern included do define_callbacks :retire default_scope { where(:retired => false) } scope :retired, where(:retired => true) end

Categories : Ruby On Rails

Calling a (helper) method from a view with two arguments
You didn't call it pages_associateplace. You called associateplace. So in your link_to you should take off the pages_ part and leave only: associateplace_path(@activity.id, place.id) There is one more thing. You've created a PUT route. But in a link_to you need to specify that it is a PUT that you want since GET is the default. So you need to write: <%= link_to "Choose Place", associateplac

Categories : Ruby On Rails

Is there a reason Ruby/Rails has not made nested indexing safe?
Some languages, like Objective-C, make method calls on a nil object return nil so these sorts of errors melt away. Rails has always taken the path of having a "whiny nil" where any method calls hard fail. This has become expected behaviour. If you want to patch your NilClass, do it completely: def NilClass def method_missing(*args) # Do nothing, return nil end end You can add this in

Categories : Ruby On Rails

FactoryGirl .update does not actually update associated object
What I would recommend, is added the association for your pictures in your campaign factory_girl. I think the problem is that you are not actually creating the associations when you are using << on the active record objects. I would try including the pry gem, and binding.pry in the update_campaign method to see if the models are being created properly. As an aside, I would also use let sy

Categories : Ruby On Rails




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.