I am trying to add a high/low priority button to a ToDo Rails app and am having trouble. The button should resort the items in the list based on high/low priority. I have created a new table with the rails generate method Priority, but I am having trouble on what I do next. How should you update the task controller to sort the tasks by order of priority?
samedi 27 juin 2015
How can I get the updated date from a bootstrap datetimepicker with the datetimepicker-rails gem
How can I get the value of the <input class="date_picker" ... when the <div class="bootstrap-datetimepicker-widget" ... is changed or updated? I need to get the value so I can update other attributes on the same page. Here is my best attempt to react to the 'changeDate' event:
$('.datetimepicker').datetimepicker().on('changeDate', function(ev){
console.log(' date changed '+ ev.date);
});
I'm unable to get any response form this event. I also opened an issue with @zpaulovics's gem but I'm not sure if this is a defect, or if I am not accessing the event correctly.
AngularJS HTTP call takes two minutes while the Rails action only takes 20 seconds, how can I debug this?
I have an AngularJS app and there's one page in my application, only one, that is taking 2 minutes to load. It is loading a bit of data, but the data itself is only 700KB and I benchmarked the entire rails action starting from the beginning until right before the render and it only takes 15-20 seconds. But when I look at the actual network call, or I put a timer before the angular http post call and then one in the success, they both show the call taking almost 2 minutes. I can't figure out what's going on between the render and the success on angular that would be causing this extreme time difference. Does anyone know how I could further debug this or possibly know what could be causing this?
The rails action just does a couple big database calls, all optimized, then does some work on the data, then the data (which is already JSONified with to_json) is rendered out.
Rails action ends with Completed 200 OK in 20458ms (Views: 913.8ms | ActiveRecord: 139.6ms)
Rails. Creating a User Controller. My Edit method does not show an ID
I'm creating a app. I've created a User Controller, and successfully created New and Create methods. Running the rails console, I can bring up any ID that I've created. I don't understand when I try to edit from the users/index.html page I'm not directed to /users/id/edit
Routes:
Prefix Verb URI Pattern Controller#Action
users_index GET /users/index(.:format) users#index
welcome_index GET /welcome/index(.:format) welcome#index
macros GET /macros(.:format) welcome#macros
faqs GET /faqs(.:format) welcome#faqs
root GET / welcome#index
users GET /users(.:format) users#index
POST /users(.:format) users#create
new_user GET /users/new(.:format) users#new
edit_user GET /users/:id/edit(.:format) users#edit
user GET /users/:id(.:format) users#show
PATCH /users/:id(.:format) users#update
PUT /users/:id(.:format) users#update
DELETE /users/:id(.:format) users#destroy
UsersController:
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(set_user_params)
if @user.save
redirect_to users_path
else
end
end
def index
@users = User.all
end
def edit
raise params.inspect
@user = User.find(params[:id])
end
private
def set_user_params
params.require(:user).permit(:name, :email, :team, :password)
end
end
index.html
<div> <%= link_to "Create New Agent", new_user_path %></div>
<% @users.each.with_index(1) do |user, index| %>
<div class="list_of_agents">
<%= user.name %><br>
<%= user.team %><br>
<%= user.id %><br>
<%= link_to "Edit", edit_user_path(user.id) %><br>
</div>
<% end %>
Heroku migrate db error unknown column
I am working on my ruby on rails project and when I run heroku db:migrate I get an error about how a column doesn't exist.
I know that this is because I had a migration file that I manually edited to remove a column I created beforehand instead of creating a new migration file.
I removed the remove_column line and migrated db my local db but when I migrate it to heroku it still runs the migration file to remove column even though the line is no longer there on the actual file.
I dropped my database and loaded the schema again but the heroku error continues to occur.
Heroku scheduler - schedule on demand (http post?)
We want to schedule/trigger jobs over HTTP.
Currently, we are using Heroku scheduler (because it doesn't need extra dyno/free) to schedule jobs. We need an ability to schedule them via HTTP POST or some other mechanism that we can trigger programmatically.
Any suggestions on how we can achieve this?
How to generate 2D array from a set of string in rails?
I need to generate 2D array in rails from a set of given strings. For example:
days =[ "Monday",
"Tuesday",
"Wednesday",
]
Now I want to create a 2D array and the data in this array will be fill by from days string in random manner.
Example:
[monday, tuesday, wednesday],
[tuesday, wednesday, monday]
...
and so on depends on given dimensions
How to do it?
Rails 4 assets not loaded in production although work on local production server
My production server won't load any Rails assets. When I run
RAILS_ENV=production rails s
I can see everything just fine. I even tried doing
RAILS_ENV=production bundle exec rake assets:precompile
Still no luck
Here is my production.rb
config.cache_classes = false
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.serve_static_files = false
config.assets.compress = false
config.assets.compile = true
config.assets.digest = false
config.eager_load = false
config.log_level = :debug
config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
ActiveSupport::XmlMini.backend='Nokogiri'
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
Rails / Bootstrap / HAML - How to convert this code to display flash messages to HAML?
I want to convert the following code to HAML to handle Bootstrap's alert messages in a Rails 4.2.2 application. I've tried manually, using html2haml and online converters and the code I get never works.
The code:
<div class="alert
<%=
case type.to_sym
when :alert, :danger, :error, :validation_errors
'alert-danger'
when :warning, :todo
'alert-warning'
when :notice, :success
'alert-success'
else
'alert-info'
end
%>
alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<%= content %>
</div>
This is what I get from converters:
.alert.case.when.:validation_errors.when.:todo.when.:success.else.end.alert-dismissible{:class => "<haml_loud> type.to_sym :alert, :danger, :error, 'alert-danger' :warning, 'alert-warning' :notice, 'alert-success' 'alert-info' </haml_loud>", :role => "alert"}
%button.close{"data-dismiss" => "alert", :type => "button"}
%span{"aria-hidden" => "true"} ×
%span.sr-only Close
= content
I know it's ugly but it is the only code I have found that works out of the box with Bootstrap 3.5.5. If anyone has suggestions for new code using HAML, I'm open to hear.
More ruby-like way of writing simple ActiveRecord code
Here is some fairly standard Ruby on Rails 4 ActiveRecord code:
def hide(user)
self.hidden = true
self.hidden_on = DateTime.now
self.hidden_by = user.id
end
def unhide
self.hidden = false
self.hidden_on = nil
self.hidden_by = nil
end
def lock(user)
self.locked = true
self.locked_on = DateTime.now
self.locked_by = user.id
end
def unlock
self.locked = false
self.locked_on = nil
self.locked_by = nil
end
# In effect this is a soft delete
def take_offline(user)
hide(user)
lock(user)
end
The code is easy to understand and doesn't try to be clever. However it feels verbose. What would be a more succinct or canonical way of specifying this code/behaviour?
How to reference a JS file from within application_helper
I have these files:
- app
-- assets
--- javascripts
---- controllers
----- company.js.coffee
----- projects.js.coffee
In my application.rb I got:
Rails.application.config.controllers_with_assets = %w( company projects )
Rails.application.config.controllers_with_assets.each do |controller|
config.assets.precompile += ["controllers/#{controller}.js"]
end
In my application_helper I got this method set up:
def controller_assets
controller = params[:controller]
if Rails.application.config.controllers_with_assets.include? controller
javascript_include_tag(asset_path('controllers/'+ controller))
end
end
This is included in the layout so that js is only loaded if the appropriate controller is also active. This all works fine in development.
In production I can see that the JS files are correctly compiled.
/public/assets/controllers/company-28b5effa0fbec2899df9a18ab1b85975.js
In the view (browser) however I see that it failed to load:
GET http://ift.tt/1TVw0kO
When I log in the console of the server and give this command:
Rails.application.assets.find_asset('controllers/company')
=> #<Sprockets::BundledAsset:0x5810768 pathname="/websites/instalane/production/releases/20150627231331/app/assets/javascripts/controllers/company.js.coffee", mtime=2015-06-27 14:21:45 +0000, digest="e7654520e52697294bb9e13ea09710e6">
What am I doing wrong?
FYI I already tried the following in the application_helper:
javascript_include_tag('controllers/'+ controller)
and
javascript_include_tag('controllers/'+ controller + '.js')
and
javascript_include_tag(controller)
Failing uniqueness validation with FactoryGirl
I'm having problems with FactoryGirl, I'm using sequence to avoid duplicating fields, but validations are failing anyway.
Output:
1) CustomersController anonymous user GET #edit is redirected to signin when accessing edit form
Failure/Error: get :edit, id: create(:customer)
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken, Email has already been taken
# ./spec/controllers/customers_controller_spec.rb:25:in `block (4 levels) in <top (required)>'
# -e:1:in `<main>'
3) Customer public class methods executes its methods correctly #find_by_id_or_name finds customer by name
Failure/Error: let(:john) {create(:customer, name: 'John Doe X')}
ActiveRecord::RecordInvalid:
Validation failed: Email has already been taken, Email has already been taken
# ./spec/models/customer_spec.rb:25:in `block (3 levels) in <top (required)>'
# ./spec/models/customer_spec.rb:38:in `block (5 levels) in <top (required)>'
# -e:1:in `<main>'
Factories:
FactoryGirl.define do
factory :customer do
user
name {Faker::Name.name}
sequence(:mail) { |n| "person#{n}@example.com" }
address {Faker::Address.street_address}
phone {Faker::PhoneNumber.phone_number}
end
end
FactoryGirl.define do
factory :user do
sequence(:email) {|i| "example#{i}@example.com"}
password {Faker::Internet.password(10)}
end
end
These are the tests that are failing:
describe "public class methods" do
let(:john) {create(:customer, name: 'John Doe X')}
let(:frank) {create(:customer)}
context "responds to its methods" do
it "responds to #find_by_id_or_name" do
expect(Customer).to respond_to(:find_by_id_or_name)
end
end
context "executes its methods correctly" do
context "#find_by_id_or_name" do
it "finds customer by name" do
customer = Customer.find_by_id_or_name('John Doe X')
expect(customer).to eq john
end
it "finds customer by id" do
customer = Customer.find_by_id_or_name(frank.id)
expect(customer).to eq frank
end
end
end
end
describe "GET #edit" do
it "renders :edit view" do
get :edit, id: create(:customer).id
expect(response).to render_template(:edit)
end
end
describe "DELETE #destroy" do
before :each do
@customer = create(:customer, user: @user)
end
it "deletes record" do
expect {delete :destroy, id: @customer.id}.to change(Customer, :count).by(-1)
end
end
This is happening to me all over my app. I just copied some tests that apply to Customer.
Thanks
Database migration stops halfway through
I've had issues trying to use PostgreSQL so changed my application to use MYSQL.
But, when I run rake db:migrate I get the following message before the migration stops:
-- PostgreSQL database dump complete
However when I run rake db:seed, I get told that I still have 303 migrations left. How can I complete this migration?
Status of Migration is Done
When I was migrating something on rails I got a problem. And now after I migrated it, the status went down. Is there anything I can do?
Rails 4 create model with nested attributes has_many
I have a many to many relationship with DoctorProfile and Insurance. I'd like to create these associations off of a form from a client side app. I'm sending back an array of doctor_insurances_ids and trying to create the association in one line. Is it possible to send back an array of doctor_insurances ids? If so what's the proper way to name it for mass assignment in the params?
The error I'm getting with the following code is
ActiveRecord::UnknownAttributeError: unknown attribute 'doctor_insurances_ids' for DoctorProfile.
class DoctorProfile
has_many :doctor_insurances
accepts_nested_attributes_for :doctor_insurances # not sure if needed
class Insurance < ActiveRecord::Base
has_many :doctor_insurances
class DoctorInsurance < ActiveRecord::Base
# only fields are `doctor_profile_id` and `insurance_id`
belongs_to :doctor_profile
belongs_to :insurance
def create
params = {"first_name"=>"steve",
"last_name"=>"johanson",
"email"=>"steve@ymail.com",
"password_digest"=>"password",
"specialty_id"=>262,
"doctor_insurances_ids"=>["44", "47"]}
DoctorProfile.create(params)
end
Defining mailer in sorcery
I am building a rails app using sorcery. When I go to users/new, there is an Argument Error stating "To use reset_password submodule, you must define a mailer (config.reset_password_mailer = YourMailerClass)"
Went into config/initializers/sorcery.rb and included code user.reset_password_mailer = UserMailer but I am still receiving the error. Within the UserMailer class, I defined reset_password_email method
def reset_password_email(user)
@user = User.find user.id
@url = edit_password_reset_url(@user.reset_password_token)
mail(:to => user.email,
:subject => "Your password has been reset")
end
and updated the sorcery.rb file
user.reset_password_email_method_name = :reset_password_email
I am still receiving the same error message.
In the Users controller:
class UsersController < ApplicationController
def index
@users = User.all
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to products_url, notice: "Signed Up!"
else
render "new"
end
end
def show
@user = User.find(params[:id])
end
private
def user_params
params.require(:user).permit(:email, :user_name, :password, :password_confirmation)
end
end
And my User model is:
class User < ActiveRecord::Base
authenticates_with_sorcery!
has_many :projects
validates :password, confirmation: true
validates :password_confirmation, presence: true
validates :email, uniqueness: true
end
Rails / Paperclip absolute_path from form?
I'm trying to save the absolute_path from the paperclip file attached in a rails form. I want to save it to the database for later use.
I read through the paperclip docs and can't find anything that I think will work. Ruby has a solution for File abstraction in the ruby-docs that I was able to get working in terminal but i'm not sure how to implement it with rails and paperclip in a form.
Any ideas would be appreciated...
Ultimately, the goal is to parse an xml file (nokogiri) and use the file path to tell paperclip where to find the images listed in the xml which are in the same folder.
Create a company and user in one, what's the standard?
I know a lot of startups and tech companies essentially allow you to register, and you end up registering a company and your user.
An example would be basecamp for example. I'd like to achieve the same thing, however I'm not quite certain on how they do it, and what the best way to do it is.
My thought is to have a user and company model, where on registration you register a company, and it accepts nested attributes for user. As in my head at least the relation is:
User belongs_to :company
Company has_many :users
and the registration is a Company#new with a company.user.build.
However for some reason this does feel a bit strange, as to me it would make more sense that you register a user, and create the company it belongs to.
I just want to lay the foundation right, so I don't start building anything massive on top of a system that isn't good.
Ruby on Rails Solving a No method Error
I'm currently going through Hartl's Ruby on Rails tutorial and I've come to a roadbloack with a failing test that I don't know how to get to pass. All of the previous tests through chapter 11 have ran correctly so I was hoping some one could help me interpret the errors.
Running:
bundle exec rake test
Gives me this
45 runs, 0 assertions, 0 failures, 45 errors, 0 skips
The first six errors are similar to this:
1) Error:
MicropostTest#test_should_be_valid:
ActiveRecord::Fixture::FormatError: ActiveRecord::Fixture::FormatError
And the rest of the errors follow this pattern:
7) Error:
UsersEditTest#test_unsuccessful_edit:
ActiveRecord::Fixture::FormatError: ActiveRecord::Fixture::FormatError
Error:
UsersEditTest#test_unsuccessful_edit:
NoMethodError: undefined method `each' for nil:NilClass
I'm not sure what an undefined method for a nil class would mean. If I need to post any more of my code/errors please let me know. Any help is appreciated. Thanks!
Why are this Rake task's depenencies being run out of order?
When running the following Rake task, :test is run after :staging.
namespace :deploy do
desc 'Deploy to staging'
task :staging => [:test, :cucumber] do
# do deployment things ...
end
end
Is this the expected behavior (I'm fairly certain it's not...) or is Rails doing something "clever" in its implementation of :test?
Env:
- Ruby 2.2.2
- Rails 4.1.12
- Rake 10.4.2
With Nested Resources in routes.rb with custom to_param, how can Strong Parameters allow created/update to permit?
I can't find something that'll lead in the right direction. Everyone else's similar issues with nested resources seems to resolve around accepts_nested_attributes_for… which I'm not trying to do. I'm not trying to save children from the parent, I'm trying to save directly from the child.
In my routes.rb, I have nested my resource
resources :parents, param: :parent do
resources :children, param: :child
end
parent and child tables both have their own id column, but also have unique index on columns parent and child respectively, which I was to be used in the URL instead of the id.
This is working fine browsing around going to the show, edit and index actions of each controller.
The problem is there are exceptions saving data.
I'm hoping the root-cause of the issue doesn't come down to a field in the child table is also called child as that's what I've used to override to_param in the model and need to keep it that way.
Navigating to the edit screen: http://ift.tt/1NmQwpd and pushing submit on the form, returns this NoMethodError exception:
NoMethodError at /parents/harry/children/sally
undefined method `permit' for "sally":String
I'm sure the problem is something to do with how my Strong Parameters line is in children_controller.rb. Can I add to require a hash of :parent and :child maybe?
def children_params
params.require(:child).permit(:child, :date_of_birth, :nickname)
end
Update 1 (Added params): Here are the request parameters:
{
"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"fAkBvy1pboi8TvwYh8sPDJ6n2wynbHexm/MidHruYos7AqwlKO/09kvBGyWAwbe+sy7+PFAIqKwPouIaE34usg==",
"child"=>"sally",
"commit"=>"Update Child",
"controller"=>"children",
"action"=>"update",
"parent_parent"=>"harry"
}
Other instance variable in-scope at time of error:
@parent
<Parent id: 1, parent: "harry", description: "", user_id: 1, created_at: "2015-06-27 12:00:15", updated_at: "2015-06-27 12:00:15">
@child
<Child id: 1, child: "sally", date_of_birth: nil, parent_id: 1, nickname: nil, created_at: "2015-06-27 12:00:15", updated_at: "2015-06-27 12:00:15">
Updating message counter on private_pub publish
I am creating a chat module for my application and using private_pub for sending and receiving messages. I want to update the unread message counter on receiver's as soon as receiver gets the message.
Each page is subscribed to a channel where message gets published, so that every time I get the message, the counter on the page gets updated.
Following js file is executed when a new message is created.
<% publish_to conversation_messages_path(@conversation.id) do %>
$("#messages").append("<%= escape_javascript render(:partial => 'message', :locals => { :message => @message })%>");
$("#unread_messages_count").text("<%= current_user.received_messages.unread.size %>");
<% end %>
// @conversation.messages.where(:read => 0)
$("#newMessageForm")[0].reset();
$("#messages").scrollTop($("#messages")[0].scrollHeight);
The page gets updated but current_user.received_messages.unread.size gives me the sender's unread count, why is this so?
This means the current_user should be different for every other page who has subscribe_to that URL. As of now current_user is the one who publish_to that URL which results in the same value of unread messages count for every different client.
One possible solution is to send the user id of the one who is currently logged in while we subscribe_to a URL and in publish_to use that to get the unread messages count but the problem is I don't know how to send data while subscribing and using it in publish.
Is it possible to add html-attributes without values in rails link_to?
I want to output an a-tag like this:
<a href="#" itemscope class="features__cta button>Stuff</a>
I know I can add html-attributes like this to the tag, but how do I add one without a value to it?
<%= link_to t('features.cta'), t('features.cta_link') , class:
'features__cta button', itemprop: "priceSpecification" %>
Rails render partial with progress bar
I'm running Rails 4 and am trying to use a bootstrap form wizard. The thing about the form wizard is that not all of its tabs should be displayed at all times.
The form wizard is in a partial that I render via $("#tab3").html("<%= j(render partial: 'wizard' ) %>"); in update_forms.js.erb (called via an ajax call).
Everything works well in this except the progress bar doesn't display (it is 0) unless I refresh the page. Any thoughts on how I can set the progress bar when rendering the partial?
Thanks!
What is the best way to store matrix in rails sqlite?
I need to create a new matrix in before_save model method. What is the best way to save this matrix, Dimension of the matrix could be max 50 * 50. How about if I store into Json?
class Simulation < ActiveRecord::Base
before_save :create_matrix
belongs_to :user
validates_presence_of :name, :message => 'Name field cannot be empty..'
def creat_matrix
if self.is_matrix
.....
end
end
end
Filter ActiveAdmin with Postgresql json column on specific json keys
I have a Deal model that features a json column called deal_info. It's actually an array of JSONs.
I'm using active admin.
For example :
deal1.deal_info = [ { "modal_id": "4", "text1":"lorem" },
{ "modal_id": "6", "video2":"yonak" },
{ "modal_id": "9", "video2":"boom" } ]
deal2.deal_info = [ { "modal_id": "10", "text1":"lorem" },
{ "modal_id": "11", "video2":"yonak" },
{ "modal_id": "11", "image4":"boom" } ]
As first step now I would like to have a filter that would enable me to filter the deals based on the fact that deal_info json column includes at least one time the modal_id in one of its included json.
It would enable me in a select dropdown to choose for example modal_id = 6 and would filter the list of Deals to only show deal 1 (see example above).
One of the further challenge is that I need to be able to remove duplicates on the select dropdown in order not to have multiple times the same id: here for example i can't have select = [4,6,9,10,11,11]...each modal_id can only appear once.
I only found this but it did not work for me.
My current Active Admin Code
ActiveAdmin.register Deal do
filter :modal_id,
as: :select
collection: deal_info.all.to_a.map ????
end
Querying Rails.cache items
I'd like to search items in my Rails.cache by their value. I'm having trouble finding out how to do this. Specifically, I'm using Active Model Serializer and would like to search through my AMS cache for keywords in their value. How do I do this?
Thanks!
Ruby csv - delete row if column is empty
Trying to delete rows from the csv file here with Ruby without success.
How can I tell that all rows, where column "newprice" is empty, should be deleted?
require 'csv'
guests = CSV.table('new.csv', headers:true)
guests.each do |guest_row|
p guests.to_s
end
price = CSV.foreach('new.csv', headers:true) do |row|
puts row['newprice']
end
guests.delete_if('newprice' = '')
File.open('new_output.csv', 'w') do |f|
f.write(guests.to_csv)
end
Thanks!
Gibbon / Mailchimp Signup Form
Having some trouble creating a simple signup form for a mailchimp list. Can't figure out why when they email passes through, it doesn't pass over to mailchimp.. thoughts? I'm sure I missed a step here.
index.html.erb (Form)
<%= form_tag('/welcome/subscribe', method: "post", id: "subscribe",) do -%>
<%= email_field(:email, :address, {id: "email", placeholder: "email address"}) %>
<%= submit_tag("Join!") %>
<% end %>
Gibbon.rb (Initializer)
Gibbon::API.api_key = "Secret API Key"
Gibbon::API.timeout = 15
Gibbon::API.throws_exceptions = false
Welcome.rb (Model)
def subscribe
@list_id = "Secret List ID"
gb = Gibbon::API.new
gb.lists.subscribe({
:id => @list_id,
:email => {:email => params[:email][:address]}
})
end
Routes.rb
Rails.application.routes.draw do
root 'welcome#index'
post 'welcome/subscribe' => 'welcome#subscribe'
end
Service PHP in Rails
I have a small PHP service that is being called in a JavaScript file by AJAX :
$.ajax({
type: "GET",
url: "getDate.php",
dataType:"json",
data :{
fromDate:fromDate,
toDate:toDate
},
success: function(data) {
......
}
});
This service contains :
$fromDate = $_GET['fromDate'];
$toDate = $_GET['toDate'];
$fromDate=date_create($fromDate);
$fromdate = date_format($fromDate,"Y-m-d")."T".date_format($fromDate,"H:i:s")."Z";
$fromdate = urlencode($fromdate);
$toDate=date_create($toDate);
$todate = date_format($toDate,"Y-m-d")."T23:00:00Z";
$todate = urlencode($todate);
$url = "http://ift.tt/1LByAtu".$fromdate."%27+and+time%3C%3D%27".$todate."%27";
$data = file_get_contents($url, false);
echo $data;
I need to use this in my Rails application. I was wondering if I could put the .php file in a Rails folder, and simply call it. Or if there's a way to do a similar service in Rails?
How to show error message on rails views?
I am newbie in rails and want to apply validation on form fields.
myviewsnew.html.erb
<%= form_for :simulation, url: simulations_path do |f| %>
<div class="form-group">
<%= f.label :Row %>
<div class="row">
<div class="col-sm-2">
<%= f.text_field :row, class: 'form-control' %>
</div>
</div>
</div>
Simulation.rb
class Simulation < ActiveRecord::Base
belongs_to :user
validates :row, :inclusion => { :in => 1..25, :message => 'The row must be between 1 and 25' }
end
I want to check the integer range of row field in model class and return the error message if it's not in the range.
Thanks in advance
Getting Rspec error no implicit conversion of Symbol into Integer with Mongoid
I'm tying to test my Rails app with Rspec, but I'm getting a no implicit conversion of Symbol into Integer error without any apparent reason. Based on the traceback I get I think the problem is related to Mongo/Mongoid, however, I can't figure out what it is exactly. The code runs perfectly in production. The error happens only when testing.
Brief look at the model without the other methods:
class Card
include Mongoid::Document
field :front, type: String
field :back, type: String
field :level, type: Integer, default: 1
field :review_date, type: DateTime, default: DateTime.now
embeds_one :card_statistic
belongs_to :topic
belongs_to :user
validates :front, :back, :level, presence: true
validates :topic, presence: { is: true, message: "must belong to a topic." }
validates :user, presence: { is: true, message: "must belong to a user." }
validates :level, numericality: { only_integer: true, greater_than: 0 }
end
One function in the model that triggers the error:
def self.reset(card)
card.update(level: 1)
end
The test code:
it "puts the given card in level 1" do
card = create(:card)
Card.correct card
card.reload
Card.correct card
card.reload
expect(card.level).to eq(3)
card.reset
card.reload
expect(card.level).to eq(1)
end
Then, the traceback of the error I get:
1) Card puts the given card in level 1
Failure/Error: Card.reset card
TypeError:
no implicit conversion of Symbol into Integer
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/server_selector.rb:56:in `[]'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/server_selector.rb:56:in `get'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/client.rb:170:in `read_preference'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/collection/view/readable.rb:318:in `default_read'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/collection/view/readable.rb:251:in `read'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/mongo-2.0.4/lib/mongo/collection/view/iterable.rb:38:in `each'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/query_cache.rb:207:in `each'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:230:in `first'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:230:in `block (2 levels) in first'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:562:in `with_sorting'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:229:in `block in first'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:474:in `try_cache'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual/mongo.rb:228:in `first'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/contextual.rb:20:in `first'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/builders/referenced/in.rb:20:in `build'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:43:in `create_relation'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:26:in `__build__'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:104:in `block (2 levels) in get_relation'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/threaded/lifecycle.rb:130:in `_loading'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:100:in `block in get_relation'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/threaded/lifecycle.rb:89:in `_building'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:99:in `get_relation'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/relations/accessors.rb:187:in `block in getter'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/validatable.rb:79:in `read_attribute_for_validation'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validator.rb:149:in `block in validate'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validator.rb:148:in `each'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validator.rb:148:in `validate'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:450:in `public_send'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:450:in `block in make_lambda'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:189:in `call'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:189:in `block in simple'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `call'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `block in simple'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `call'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:190:in `block in simple'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:92:in `call'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:92:in `_run_callbacks'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:734:in `_run_validate_callbacks'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations.rb:395:in `run_validations!'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations/callbacks.rb:113:in `block in run_validations!'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:88:in `call'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:88:in `_run_callbacks'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activesupport-4.2.0/lib/active_support/callbacks.rb:734:in `_run_validation_callbacks'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations/callbacks.rb:113:in `run_validations!'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations.rb:334:in `valid?'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/validatable.rb:97:in `valid?'
# /home/huesitos/.rvm/gems/ruby-2.2.0/gems/activemodel-4.2.0/lib/active_model/validations.rb:371:in `invalid?'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/updatable.rb:114:in `prepare_update'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/updatable.rb:139:in `update_document'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/savable.rb:25:in `save'
# /home/huesitos/.rvm/gems/ruby-2.2.0/bundler/gems/mongoid-c61547d5ed15/lib/mongoid/persistable/updatable.rb:52:in `update'
# ./app/models/card.rb:57:in `reset'
# ./spec/models/card_spec.rb:32:in `block (2 levels) in <top (required)>'
The error is also triggered when testing the controllers. Even doing a get :index throws the error. Thanks in advance for your help.
Rails]Dynamically generate static pages
I want to be able to publish webpages with my rails app. In other words, there's a button that says "submit current page" and when the user presses this button, there should be a new page with its own url. When you make a new post, there's a new webpage generated at posts/1.
<div>
Save me at /pages/one
</div>
<button>Make</button>
<div>
Save me at /pages/second
</div>
<button>Make</button> <- upon pressing this, there should be a new static page
Is there a convention to follow?
Editable Webpage Table in Rails
I am trying to make a webpage with a calendar similar to the one in the following link:
http://cs61a.org/
But I need the page to be editable. I want the user to not only be able to change the contents of the table but also the table structure (Add columns etc). What strategy should I use to tackle this problem?
Rails 4 Include Helper inside Service Object
I am currently trying to use a Devise helper inside a service object
class ServiceObject
include Devise::Controllers::Helpers
But I get
undefined method `helper_method' for ServiceObject:Class
Any idea how to use such a helper inside the service object?
rails 4 undesired double pop-up
In my rails 4 application session expire time set to 10 minutes for user login.
After that user clicks on any link the default flash message is comes up like Your session is expired. Please sign in again to continue.
This is fine, but below this another flash message is coming like "true" . I don't know from where it is coming from, how can I solve this?
Postgre error with Rails - I'm running locally but the database won't work properly)
Currently trying to install to run Catarse on my Mac (Yosemite)
When I try and run rake db:create db:migrate db:seed
I get the following message
ActiveRecord::StatementInvalid: PG::DuplicateObject: ERROR: role "admin" already exists
: CREATE ROLE admin NOLOGIN;
-- This script assumes a role postgrest and a role anonymous already created
GRANT usage ON SCHEMA postgrest TO admin;
GRANT usage ON SCHEMA "1" TO admin;
GRANT select, insert ON postgrest.auth TO admin;
GRANT select ON ALL TABLES IN SCHEMA "1" TO admin;
GRANT admin TO postgrest;
I have tried to do the above but to no avail, and now it's saying that I have a duplicate admin role. Can anybody please offer some guidance or assistance?
I've spent most of the day troubleshooting and looking at this over and over again in frustration by doing the following:
Uninstalling catarse Reinstalling and uninstalling postgresql Trying to implement the above 'GRANT' commands
Why is it too slow to fetch the records?
I'm using the gem called 'yourub' to fetch information of multiple videos narrowed down by particular keyword.
My code is just like this and it works fine but too slow until the result start showing up on the page.
Is it because I'm using the gem? Does it get faster if I do the same thing with native way of using "google-api-client" gem? If so how can I replace my original?
P.S. According to the document of 'yourub', it only can fetch up to 50 videos:( and it cannot even choose which page of the result to show with pagination select :(
My code(View)
<% client = Yourub::Client.new %>
<% client.search(query: "cat", order: "date", max_results: 30) do |video| %>
Video ID:<%= video["id"] %> <br />
Title: <%= video["snippet"]["title"] %><br />
<img src="<%= video["snippet"]["thumbnails"]["high"]["url"] %>" with="480" height="360"><br />
----------------------------------------------------------------------------------------------<br />
<br />
<% end %>
has_many :through broke some code
So i'm relatively new to RoR, and am having some issues in trying to get my code back up and working. So previously I had users, and wikis that users could create. I've set up so that users can subscribe and get premium status to make wikis private. Now I'm in the process of making it so that Premium users can add standard users as collaborators to the wiki. I've decided to got about associating them through has_many :through relationships.
The issue I'm running into so that some of my buttons have started making errors that I don't understand. The one I'm stuck on right now is when showing the page that has a create new wiki button on it.
This is the error I am getting when I added the has_many through: relationship
No route matches {:action=>"new", :controller=>"wikis", :format=>nil, :user_id=>nil} missing required keys: [:user_id]
Here are the models:
collaborator.rb
class Collaborator < ActiveRecord::Base
belongs_to :wiki
belongs_to :user
end
user.rb
class User < ActiveRecord::Base
...
has_many :collaborators
has_many :wikis, :through => :collaborators
end
wiki.rb
class Wiki < ActiveRecord::Base
belongs_to :user
has_many :collaborators
has_many :users, :through => :collaborators
end
The important bits of the wiki_controller.rb
def new
@user = User.find(params[:user_id])
@wiki = Wiki.new
authorize @wiki
end
def create
@user = current_user
@wiki = @user.wikis.create(wiki_params)
authorize @wiki
if @wiki.save
flash[:notice] = "Wiki was saved"
redirect_to @wiki
else
flash[:error] = "There was an error saving the Wiki. Please try again"
render :new
end
end
And finally the show.html.erb file the button is located in.
<div class="center-align">
<%= link_to "New Wiki", new_user_wiki_path(@user, @wiki), class: 'btn grey darken-1' %>
</div>
If I'm missing any files or relevant info please let me know. This may be a simple stupid answer but I'm stuck for the life of me.
Thanks in advance.
Edit:
Here is the requested added info, first up the show info in the users_controllers.rb
def show
@wikis = policy_scope(Wiki)
end
the corresponding policy scope I'm using in the user_policy.rb
class UserPolicy < ApplicationPolicy
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
def resolve
wikis = []
all_wikis = scope.all
all_wikis.each do |wiki|
if wiki.user == user || wiki.users.include?(user)
wikis << wiki
end
end
end
wikis
end
end
and the route.rb file
Rails.application.routes.draw do
devise_for :users
resources :users, only: [:update, :show] do
resources :wikis, shallow: true
end
resources :wikis, only: [:index]
resources :charges, only: [:new, :create]
delete '/downgrade', to: 'charges#downgrade'
authenticated do
root to: "users#show", as: :authenticated
end
root to: 'welcome#index'
end
Hope it helps
create two connections MySQL on Rails project
I should create a CRM(Customer relationship management) in Rails.In this CRM i have to use two databases(MySQL).I have a doubt in the correct use of these databases.I mean, i read on internet that is possible to open two connections in a Rails project, but is this the right way to hit the problem? is really good to open two connection in a project?is it used?if not, what is the solution in the state of art(maybe the simpler to manage queries) for my problem?
Ruby on rails flash notice error
I have a problem with flash[:notice] = "Message" in Ruby on Rails.
I am trying to create login fault error message. My login fault handling is:
flash[:notice] = "Invalid username/password combination."
redirect_to(:action => 'login')
For the reason I don't know, alert just doesn't show up. I have red tons of possible solutions, but all of them just doesn't work for me. I am using Safari / Google Chrome web browsers.
checkboxs in a table created via form_for
I'm new to RoR so apologies if the answer is super simple. I'm trying to create a table that allows users to select other users that can collaborate on a wiki. The issue I'm having is that no matter which checkbox you select on the table. It only toggles the topmost option.
here is the code in question:
<%= form_for [@wiki, @wiki.collaborators.build] do |f| %>
<table class="bordered hoverable">
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.name %></td>
<td class="right-align"><%= f.check_box :user_id %><%= f.label :user_id, "Give Access" %></td>
</tr>
<% end %>
</tbody>
</table><br /><br />
the controller values in new
def new
@wiki = Wiki.find(params[:wiki_id])
@collaborator = Collaborator.new
@users = (User.all - [current_user])
end
Any help would be appreciated. Thanks in advance.
rails join query between two tables with similar field
I have 3 models
class Company < ActiveRecord::Base
has_many : CompanyAccount
has_many : CompanyContact
end
class CompanyContact < ActiveRecord::Base
belongs_to : Company
end
class CompanyAccount < ActiveRecord::Base
belongs_to : Company
end
As both the CompanyAccount and CompanyContact models belong to the Company model, they have a similar "company_id" field. I have retrieved some Accounts through a query:
@CompanyAccounts = CompanyAccount.where.not(balance:nil)
Now, using the common company_id field I am trying to retrieve all the data from my CompanyContacts table that belong to the same Company associated with the CompanyAccounts I queried above (in other words, I am trying to get the rows which have the same company_id). I have made several attempts using "joins" but everything failed so far. Could anyone give me what would be the appropriate syntax in this context? Thanks.
Rails force instance variable declaration before use on view
Is it possible to force Ruby/Rails to throw an error when printing/using instance variables on a view that haven't been defined on controller
I'm declaring an instance variable on a Rails Controller and I'm printing its value on a View
def controller_action
@some_data = "some value"
end
Then we know we can print its value on a view
<p>Some data has <%= @some_data %></p>
My problem is when doing mistakes on a view like this:
<p>Some data has <%= @somedata %></p>
Ruby won't complain and it's difficult to find those mistakes. This also applies for team development where some programmer can create an instance variable on a controller with one name and another programmer expects to print it on a view but accidentally uses other name.
How to display error messages in a multi-model form with transaction?
Two models, Organization and User, have a 1:many relationship. I have a combined signup form where an organization plus a user for that organization get signed up.
The problem I'm experiencing is: When submitting invalid information for the user, it renders the form again, as it should, but the error messages (such as "username can't be blank") are not displayed. The form does work when valid information is submitted and it does display error messages for organization, just not for user.
How should I adjust the code below so that also the error messages for user get displayed?
def new
@organization = Organization.new
@user = @organization.users.build
end
def create
@organization = Organization.new(new_params.except(:users_attributes))
#Validations require the organization to be saved before user, as user requires an organization_id. That's why users_attributs are above excluded and why below it's managed in a transaction that rollbacks if either organization or user is invalid. This works as desired.
@organization.transaction do
if @organization.valid?
@organization.save
begin
@organization.users.create!(users_attributes)
rescue
# Should I perhaps add some line here that adds the users errors to the memory?
raise ActiveRecord::Rollback
end
end
end
if @organization.persisted?
flash[:success] = "Yeah!"
redirect_to root_url
else
@user = @organization.users.build(users_attributes) # Otherwise the filled in information for user is gone (fields for user are then empty)
render :new
end
end
The form view includes:
<%= form_for @organization, url: next_url do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_field :name %>
# Other fields
<%= f.fields_for :users do |p| %>
<%= p.email_field :email %>
# Other fields
<% end %>
<%= f.submit "Submit" %>
<% end %>
The error messages partial is as follows:
<% object.errors.full_messages.each do |msg| %>
<li><%= msg.html_safe %></li>
<% end %>
Heroku not updating website after successful deploy
I'm trying to deploy my app through Heroku, using Ruby on Rails, and I have been successful in the past but now when I use the same commands as before it will deploy successfully but when I visit my website it has not been updated with my new code.
Here are the commands I am using:
git add -A
git commit -m "message"
git push
git push heroku
heroku run rake db:migrate
I tried using "git push heroku master" as well based on another stack overflow thread but it didn't update my website either. Running the deployment only returns one warning and that is that my Ruby version is not declared so I don't think that would be an issue. I'd be happy to provide more information if I need to. Any information/help would be greatly appreciated.
How to load asset gems only for precompile on heroku?
Rails 4.1+, so there isn't built-in support for an :assets group
I want to keep Heroku's precompile on push behaviour, but don't want the asset gems loaded by the rails server. We don't use any kind of inline coffeescript or scss template rendering in the app, only in the assets, so it's just wasted memory at runtime.
I've played around with extending the rake task, configuring sprocket-rails, and even changing application.js to application.js.erb and adding things like
//= <% require 'jquery-rails' %>
//= require 'jquery'
but still get these errors:
Sprockets::FileNotFound: couldn't find file 'jquery'
If I keep the asset gems in the default Gemfile group everything works fine.
The point here is to not have them loaded in the production environment, but to have
RAILS_ENV=production rake assets:precompile task
load them before it executes (and fails because of missing libraries)
wrong singular for 'slaves'
I have a line resources :slaves in my routes.rb. Which is definitely plural for 'slave', but rails thinks that it's plural form of 'slafe', so I get paths like new_slafe_path. Is there a way to tell rails correct singular form without explicitly specifying each route?
Undefined method "errors"... But there are ERRORS
I am doing a basic validation for a bank entry and am trying to display the errors on submit. Here is my validation and html.
class GuestbookEntry < ActiveRecord::Base
validates :body, presence: :true
end
This is my html:
<% form_for @guestbook_entry do |f| %>
<% if @guestbook_entry.errors.any? %>
<% @guestbook_entry.errors.full_messages.each do |m| %>
<li><%= m %></li>
<% end %>
<% end %>
<%= f.label :body, "Guestbook Entry:" %>
<%= f.text_area :body %>
<%= f.submit "Submit" %>
<% end %>
Any ideas?
Rails 4.1 - Write to MySQL database without typecasting
I have a column in my MySQL database which is of type TINYINT(1). I need to store actual integers in this column. The problem is, because of the column type, Rails 4.1 assumes this column contains only boolean values, so it typecasts all values besides 0 or 1 to be 0 when it writes to the database.
I don't want to simply disable boolean emulation since we have a number of columns in our database where we use TINYINT(1) to actually represent a boolean value.
How can I force Rails 4.1 to bypass the typecasting step and write directly to the database instead?
(This excerpt from the Rails 4.1 source may be of some use: http://ift.tt/1BWF1og)