w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » RUBY ON RAILS » Page 5
Is there anyway to create a centralized partial in Rails 4?
You can actually render partials from any folder. For example, in users/show.html.erb you can render a partial _info from, say, transactions. <%= render 'transactions/info' %> A common thing to do is to put such shared partials into a separate directory with a descriptive name (I use "shared"). <%= render 'shared/filter_panel' %>

Categories : Ruby On Rails

Updating rails has_many through relations
First solution: def self.update_agency_specializations(agency, params) attributes = params.require(:agency).permit( { cruise_line_ids: [] } ) agency.cruise_line_ids = attributes[:cruise_line_ids].select{ |x| x.to_i > 0 } agency.save end !agency.errors.present? end In short, don't build anything. Let Rails do the job. Second solution: def self.update_agency_specializations(ag

Categories : Ruby On Rails

error while loading route: - why am I not retrieving data form rails?
The promise returned by your model hook is rejecting. To found out why, replace the code in your model hook with this: App.PostsRoute = Ember.Route.extend({ model: function () { return this.store.find('post').catch(function (error) { debugger; }); } }); When you load the route in your browser, the debugger call will pause execution, and allow you to look at the error being rep

Categories : Ruby On Rails

Rails compare time column with now
First, you should move your logic to your model. Second, the Rails :time datatype still stores a date into the database (even though it isn't used). We'll have to manually strip the date: Class Course < ActiveRecord::Base def status t = Time.now.utc.strftime("%H%M%S%N") end_time_f = self.end_time.utc.strftime("%H%M%S%N") begin_time_f = self.begin_time.utc.strftime("%H%M%S%N")

Categories : Ruby On Rails

Automatically defining a variable in Rails console
If you're fine with instance variables, you can add those to ~/.pryrc @f = Foo.last With local variables this won't work, because they're local to their scope (hence the name). What I do myself, is have all of the "setup" commands in a separate text file. Then in the new rails console, I just paste it. I don't have to re-type the same definitions with every console restart No pollution in t

Categories : Ruby On Rails

Create action not saving data on the database
Writing here since in the comments we don't get nice formatting: Let's make it easier. I assume your controller is called CountriesController so: Remove that default route & add resources :countries in your routes. Next, in the form: <%= form_for(@country, url: countries_path) do |f| %> ... <% end %> Now you should see in the logs that you are making a POST request. You can

Categories : Ruby On Rails

Can't convert Hash to JSON before :show action
You can visit below link http://www.rexfeng.com/blog/2012/12/convert-a-ruby-hash-into-valid-json/ I think you have to write require 'json'

Categories : Ruby On Rails

Rails erb alterantive to fields_for find specific record
<%= f.fields_for group_parameters, @specific_records do | builder | %> Attribute <%= builder.text_field(:name) %> <% end %> Fetch data from DB as per your criteria and assign to @specific_records

Categories : Ruby On Rails

Rails Call Custom Controller Action from Custom Form
Yah, I got your point. So you wanted the following thing: You wrote an custom action You wanted to submit a form that action You have registered your action in the router. So let me answer the following solutions and find some mistakes you made in your code. # in route.rb resources :exchanges do patch :update_ordid, on: :member # this is the best practice I would say, #when you ar

Categories : Ruby On Rails

How to implement a HABTM in Ember?
Well, at a minimum you're going to need to add a couple of belongs-to relationships on your appointment model: App.Appointment = DS.Model.extend({ ... physician: DS.belongsTo('physician'), patient: DS.belongsTo('patient'), ... }); Thus, whenever an appointment is saved, its child relationships will be saved with it. I assume that's what you want, since that's how the db is structured in

Categories : Ruby On Rails

Active Admin - dropdown for row
I was able to get it to work, and I still have no clue as to why I needed to insert a blank string at the beginning of the collection array. Perhaps this has to do with active admin changing the formatting around. This is what I came up with for anyone who runs into this problem: panel 'Law Firm'do table_for(bc_user) do column 'Law Firm' do select :law_firm_id, collection: options_for

Categories : Ruby On Rails

How to call function in ruby
In Ruby, you must first define a method. You do that using the syntax def method_name # code goes here end To call the method, you simply type in the method name method_name In your case, you had the first step down def install_apache end You need to add another line in your code like so install_apache

Categories : Ruby On Rails

Bootstrap-saas not showing up glyphicons-halflings.png
Bootstrap 3 switched from using bitmap icons (PNG) to icon fonts, so glyphicons-halflings.png are no longer in Bootstrap (hence the error): instead a set of icons is loaded as a font, each separate icon is placed using CSS classes with certain font-family and content (in a nutshell, in fact it's a bit more complicated). Migration from 2.x will be tedious, that's for sure. In fact, there is a migr

Categories : Ruby On Rails

What's a good way to include code from a .rb file in my controller?
Normally this is handled with Concerns in Rails 4. You can achieve a similar effect in Rails 3 by declaring a module and using that: module SpreadsheetCreator def create_spreadsheet # ... end end So long as this is named spreadsheet_creator.rb and is in a path that the ActiveSupport autoloader can find it, you don't need to do anything special to include it. app/helpers or app/models sh

Categories : Ruby On Rails

Rspec 3: can't check class type
Your validator method is returning the class DefaultValidator and/or BaseValidator. In other words, those are not instances of those classes, but their class is Class. The be_a and be_a_kind_of matchers are for asserting that an object is an instance of the Class or Module argument that is passed to them. That's why your first code sample fails, but the second one passes. The second code snippet

Categories : Ruby On Rails

Rails 4 ActiveRecord has_many length condition
Not a direct answer to your actual question, rather an alternative, but you get a big performance boost on association counts using the 'counter_cache' feature in rails: class Student belongs_to :school, :counter_cache => true You also need to add a 'students_count' column to the schools table, with a default of 0. Then when an association is created/deleted this counter is automatically u

Categories : Ruby On Rails

Search statistics on Searchkick
I would try using the "conversions" feature from searchkick. You can use that to persist queries as listed in the readme. I haven't tried it myself, but I would thisnk Redis would be a good choice to persist these data.

Categories : Ruby On Rails

Call a Model that has no controller from another file
There is a nice blogpost which gives you the rundown on how to connect to ActiveRecord without rails. In a nutshell, you need to require your AR files, and then call establish_connection with the correct configuration: Active record works just fine and dandy without rails, but it needs things to be just so. To start, get the gem and add it to your gemfile. Next, make all of your classes i

Categories : Ruby On Rails

Create an array with different sales created at the same time Ruby on Rails
If you want to group all of your sales you should be able to do: Sales.all.group(:client_id, :created_at) Or if you're trying to group by :created_at and then :client_id just switch the order. Though just a note, I would not recommend grouping by :created_at since, unless your processing tons of transaction, you will rarely have the duplicate times. You don't need to write raw SQL since Active

Categories : Ruby On Rails

rails 4 hide a model attribute before rendering
For the JSON you can override as_json on the model: def as_json(options={}) options.reverse_merge! except: :accesstoken super(options) end For the logging, in config/application.rb you can add the attribute to the filter list config.filter_parameters << :accesstoken

Categories : Ruby On Rails

Nginx does not cache cross domain requests (CORS)
The problem was in rails (not in nginx). Rails add "Set-Cookie" header for cross domain requests even if cookie is already set (I don't know why, maybe it's rails bug). So my solution is: proxy_ignore_headers "Set-Cookie";

Categories : Ruby On Rails

Circular dependency detected while autoloading constant (ActiveRecord)
This is a classical example of a copy-paste mess - I've copied the code of Location.rb into Assignment.rb, edited it but forgot to re-name the class. So I end up having two Location models - in 2 different rb files. Doh!

Categories : Ruby On Rails

Count of a count with Rails
You can use inject on the hash. song_values = Usage.group(:song_id).count.values times_used = song_values.inject({}) do |used, count| if used[count].nil? used[count] = 1 else used[count] += 1 end used end You could use a ternary operator if you want the if/else to be one line used[count].nil? ? used[count] = 1 : used[count] += 1 This is just looping over the songs usage coun

Categories : Ruby On Rails

Creating a new object when creating another
This should work: def create @team = Team.new(team_params) @team.save @team_player = current_account.build_player_team(:account_id => current_account.id, :team_id => @team.id) @team_player.save respond_with(@team) end Build on it's own won't save, and saving the parent won't do anything. You need to use build_player_team, or use create() instead of build. Either would work. def

Categories : Ruby On Rails

How to use rails_admin with Sinatra?
I don't think it can be easily done. rails_admin relies on models being backed by ActiveModel, so you cannot feed it with your plain-ruby models. You can try someting like this though https://github.com/ratnakarrao-nyros/sinatra-admin, but it doesn't look that well maintained.

Categories : Ruby On Rails

Multiple check box not working Rails 4
There are no service_ids in advertisement_params. Add them: @advertisement = Advertisement.new(advertisement_params.merge(service_ids: params[:service_ids])) # or @advertisement = Advertisement.new(advertisement_params) @advertisement.service_ids = service_ids

Categories : Ruby On Rails

Turn flat file into relational models
Just for the sake of merging my comment and @anton-z 's. You can use activerecord-import for doing bulk operations, and ActiveRecord's find_or_create_by to do the checking.

Categories : Ruby On Rails

Rails has_one one-way association that is not obligatory
The best thing was to refuse from using nested_attributes_for and create two different objects. And later create or update them in trasaction if needed. That will remove all complexity and problems related to building unnecessary things before they are really needed.

Categories : Ruby On Rails

rails render page as json
Try to change your function: def getOffersByURL @my_model= Mymodel.where(attr1: params[:url], :validFrom => {:$lte => Time.now}).all respond_to do |format| format.json { render json: @my_model } format.html { @my_model } end end What happens if you try to show your json like this in your view: <%= @my_model.to_json %> Do you have any data c

Categories : Ruby On Rails

Rails4 - How to create a HTML button for a link?
you are looking for button_to http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to <%= button_to "Activate", edit_account_activation_url(@user.activation_token,email: @user.email) %> should do what you want.

Categories : Ruby On Rails

Make sure crawlers don't 'click' on button
Some time ago I found myself in a similar situation and I wrote a negative captcha plugin for Rails: https://github.com/markets/invisible_captcha. It's based on the honeypot strategy, the idea was to provide a better user experience. More or less, you should add into your form: <%= form_tag(new_demo_path, :method => "put", id: "demo-form") do %> <%= invisible_captcha %> <% en

Categories : Ruby On Rails

Additional html.erb file in View not Working in ruby on rails
For the helper new_second_path to work, you have to uncomment the line resources :seconds in the routes. Unless you know what you are doing, I would comment the line match ... which is a catch-all. Also: a path /second/count will not work, it should be /seconds/count. To explain this: /second/count: with your match it will look for SecondController (singular!!) and action count But the cl

Categories : Ruby On Rails

Install Mac OS on VirtualBox for Windows using iatkos to run a ruby on rails project :/
I think there is no need to go for Mac OS. If you have Window System, Set up the Vagrant Dev Environment. It will provide rails platform to run ROR projects i.e Linux. Install VirtualBox https://www.virtualbox.org/ Install Vagrant http://www.vagrantup.com/ Create a directory where you wanna clone rails app. Clone rails-dev-box repo https://github.com/rails/rails-dev-box Go into rails-dev-box fo

Categories : Ruby On Rails

"The page you were looking for doesn't exist." edit form
The first parameter is where the form submission should go (update). http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-form_tag

Categories : Ruby On Rails

How to add unique: true to already existing column
Remove the old index and add it again with the new constraint: def change remove_index :editabilities, [:user_id, :list_id] add_index :editabilities, [:user_id, :list_id], unique: true end (Credit: I directly lifted this answer from Baldrick's answer here. Upvote him before you upvote me ;) )

Categories : Ruby On Rails

How do I save parameters in the database in rails?
I would use attr_accessor to store the relevant params from the form, and then have a before_validation method to look at these and calculate the fare. This can do the calculation for the fare and write it into the database. eg #in booking attr_accessor :foo before_validation :calculate_fare_if_foo def calculate_fare_if_foo unless self.foo.blank? #do some calculation based on foo and

Categories : Ruby On Rails

Data is not fully shown in column chart chartkick and rails
I removed the controller part and the added in the view like this <%= column_chart @DataGovernances.map{|gov| { name: "Tests", DataGovernance.where(company_id: current_dashboard_user.company_id.to_s).group(:entry_date).sum(:no_of_tests)} like the same for the rest }

Categories : Ruby On Rails

before_destroy callback on rails
I prefer to use methods instead of the anonymous blocks. I would handle this as follows: class Record < ActiveRecord::Base before_save :remember_new_record after_save :write_save_notification before_destroy :write_destroy_notification # ... the rest of your class ... private def remember_new_record @is_new_record = self.new_record? end def write_save_notific

Categories : Ruby On Rails

Rails acts_as_votable gem ordering
Your get_likes- method will not work with an order-scope, because the sort order is executed on the database and your method's data is unknown to the database. You could sort your records in ruby, using array methods, but that is slow and this operation should be done at database level. By using counter-caches which store the number of counts for a record in a column you can sort in the databas

Categories : Ruby On Rails




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