dimanche 31 janvier 2016
vendredi 29 janvier 2016
NoMethodError (undefined method `id' for nil:NilClass): in Rails 4.0.2
Can anyone help with this?Thanks in advance for your reply.
In app/controllers/heats_controller.rb, the code is as below:
class HeatsController < ApplicationController
def add_car
Pusher[params[:sendTo]].trigger('addCar', car_params)
head :ok
end
def index
@heats = Heat.all
render json: @heats
end
def new
race = Race.all.sample
render json: { start_time: Time.now.to_s,
race_id: race.id,
text: race.passage }
end
def show
@heat = Heat.find(params[:id])
end
def start_game
Pusher[params[:sendTo]].trigger('initiateCountDown', start_heat_params)
head :ok
end
def update_board
Pusher[params[:channel]].trigger('updateBoard', car_params)
head :ok
end
private
def heat_params
params.require(:heat).permit(:race_id)
end
def car_params
params.permit(:racer_id,
:racer_name,
:return_to,
:progress,
:racer_img,
:wpm,
:channel,
:sendTo)
end
def start_heat_params
params.permit(:channel, :race_id, :text, :timer)
end
end
In app/models/heat.rb, the code is as below:
class Heat < ActiveRecord::Base
belongs_to :race
has_many :racer_stats
end
Any help will be appreciated ,thank you
jeudi 28 janvier 2016
undefined method `name' for nil:NilClass when deleting association
I am using Rails 3.2.13 I have 3 entities
Mother
class Mother < ActiveRecord::Base
attr_accessible :previous_births_attributes
belongs_to :participant
has_many :previous_births
accepts_nested_attributes_for :previous_births, :reject_if => :all_blank, allow_destroy: true
end
PreviousBirth
class PreviousBirth < ActiveRecord::Base
attr_accessible :gender
belongs_to :mother
end
I displayed my view using cocoon
_form.html.erb
<div id='previous-births'>
<%= f.simple_fields_for :previous_births do |task| %>
<%= render 'previous_birth_fields', :f => task %>
<% end %>
<%= link_to_add_association 'add previous birth', f, :previous_births, class: 'btn btn-success btn-mini ' %>
</div>
_previous_birth_fields.html.erb
<div class="nested-fields row">
<table class="table table-compact span12">
<thead>
<tr>
<th class="span1">Gender</th>
<th class="span1"> </th>
</tr>
</thead>
<tbody>
<tr>
<td><%= f.input_field :gender, collection: ["Female", "Male"], :class => "span1" %></td>
<td><%= link_to_remove_association "remove", f, class: 'btn btn-danger btn-small span1' %></td>
</tr>
</tbody>
Adding previous_birth works like a charm. But when I remove association during update, I get
NoMethodError (undefined method
name' for nil:NilClass): app/controllers/mothers_controller.rb:71:in
block in update' app/controllers/mothers_controller.rb:70:in `update'
mothers_controllers.rb
def update
@mother = Mother.find(params[:id])
participant = @mother.participant
authorize participant
respond_to do |format|
if @mother.update_attributes(params[:mother]) #line 71
format.html { redirect_to @mother.participant, notice: 'Mother was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @mother.errors, status: :unprocessable_entity }
end
end
I do not have an attribute called name in either mother or previous birth entities. I tried to google it, but found nothing. Does anyone have any idea?
Thank you
Rails 4 ActiveRecord::AssociationTypeMismatch in JobsController#create
In trying to create a new job for a boat and get the ActiveRecord::AssociationTypeMismatch error. The specific error message is "User(#70281252898540) expected, got Fixnum(#70281243046520)"
I also tried to create a job via the rails console, and it rolled back the transaction. Can anyone help debug my code, please?
class BoatsController < ApplicationController
def new
@boat = Boat.new
end
def create
@boat = Boat.create(boat_params)
if @boat.save
redirect_to @boat
else
render :new
end
end
def show
@boat = Boat.find(params[:id])
@job = Job.new
end
private
def boat_params
params.require(:boat).permit(:name, :max_container, :location, :user_id, :avatar).merge(user_id: current_user)
end
end
class JobsController < ApplicationController
def create
@job = Job.new(job_params)
redirect_to @job.boat
end
private
def job_params
params.require(:job).permit(:name, :cost, :description, :origin, :destination).merge(user: current_user, boat_id: params[:boat_id])
end
end
User.rb
class User < ActiveRecord::Base
has_many :boats
has_many :jobs
end
Boat.rb
class Boat < ActiveRecord::Base
belongs_to :user
has_many :jobs
has_attached_file :avatar, :styles =>
{ :medium => "300x300>", :thumb => "100x100>" },
:default_url => "/images/:style/missing.png"
validates_attachment_content_type :avatar,
:content_type => /\Aimage\/.*\Z/
validates :name, uniqueness: true
validates :location, inclusion: { in: %w(New\ York Florida Russia England Ireland Norway Singapore New\ Jersey), message: "%{value} is not a valid location"}
end
Job.rb
class Job < ActiveRecord::Base
belongs_to :user
belongs_to :boat
validates :name, uniqueness: true
validates_numericality_of :cost, :greater_than =>
1000, :only_integer => true, :allow_nil => true, :message => "Must be
greater than 1000"
validates_length_of :description, minimum: 50
validates :origin, :destination, inclusion: { in: %w(New\ York Florida Russia England Ireland Norway Singapore New\ Jersey), message: "%{value} is not a valid location"}
end
Schema
create_table "boats", force: :cascade do |t|
t.string "name"
t.string "max_container"
t.string "location"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
end
add_index "boats", ["user_id"], name: "index_boats_on_user_id"
create_table "jobs", force: :cascade do |t|
t.string "name"
t.decimal "cost"
t.string "description"
t.string "origin"
t.string "destination"
t.integer "user_id"
t.integer "boat_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "jobs", ["boat_id"], name: "index_jobs_on_boat_id"
add_index "jobs", ["user_id"], name: "index_jobs_on_user_id"
create_table "users", force: :cascade do |t|
t.string "name"
t.string "username"
t.string "password_digest"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
end
Routes.rb
resources :users
resources :boats do
resources :jobs , shallow: true, only: [:create, :edit, :destroy]
end
Boats/show.html.erb
<ul>
<li><p>Boat Name: <%= @boat.name %></p></li>
<li><p>Max Container Amount: <%= @boat.max_container %></p></li>
<li><p>Boat location: <%= @boat.location %></p></li>
</ul>
<%= image_tag @boat.avatar.url %>
<h4>Add Jobs here!</h4>
<%= form_for [@boat, @job] do |f| %>
<%= f.text_area :name, placeholder: "Job Name" %>
<%= f.text_area :cost, placeholder: "Job Cost" %>
<%= f.text_area :description, placeholder: "Job Description" %>
<%= f.text_area :origin, placeholder: "Job Origin" %>
<%= f.text_area :destination, placeholder: "Job Destination" %>
<%= f.submit "create job" %>
<% end %>
<% @boat.jobs.each do |f| %>
<p><%= job.name %> (<%= job.user.name %>)</p>
<% end %>
Undefined Method when Refreshing Rails partial with AJAX
I am struggling with how to reload a partial with Rails and AJAX, and am getting an Undefined Method error. I think this may be because I am not properly passing local variables back to the partial, but I'm not sure how this should work.
I have a "Projects" Show.html.erb page. On that show page there is a certain DIV for "Investments" associated with that Project.
Show.html.erb
<div class="col-md-3" id="investments-container">
<%= render 'proj_investments' %>
</div>
It then renders a partial that cycles through all of the Investments associated with the Project (it groups by Reward type), in the _proj_investments.html.erb partial. There is a form submission in each that allows somehow to hit the INVEST button and create a new investment using AJAX. ( <%= form_for [@investment, Investment.new], remote: true, "data-type" => :js do |f| %> )
_proj_investments.html.erb
<% if @project.rewards.any? %>
<% @project.rewards.each do |reward| %>
<div class="panel panel-default project-rightpanel">
<div class="project-rightpanel-header">
<span class="project-rightpanel-header amount"><%=number_to_currency(reward.amount,precision: 0)%></span>
<span class="project-rightpanel-header amount"><%=reward.rewardtype.name %></span>
</div>
<div class="project-rightpanel-header">
<%=reward.investments.count(:amount)%> investments for <%=number_to_currency(reward.investments.sum(:amount),precision: 0)%>
</div>
</div>
<%= form_for [@investment, Investment.new], remote: true, "data-type" => :js do |f| %>
<div class="field">
<%= f.hidden_field :amount, :value => reward.amount %>
<%= f.hidden_field :User_id, :value => current_user.id %>
<%= f.hidden_field :Reward_id, :value => reward.id %>
</div>
<div class="actions">
<%= f.submit "INVEST", :class => "btn btn-success" %>
</div>
<% end %>
</div>
<% end %>
<% end %>
The Investments controller then calls the Create method and responds to JS and calls my create.js.erb
investments_controller.rb
def create
@investment = Investment.new(investment_params)
respond_to do |format|
if @investment.save
format.js {}
format.html { redirect_to @investment, notice: 'Investment was successfully created.' }
format.json { render :show, status: :created, location: @investment }
else
format.html { render :new }
format.json { render json: @investment.errors, status: :unprocessable_entity }
end
end
end
In the create.js.erb I just want to refresh everything that was in that original proj_investments partial. But, when I load it, it gives me an "Undefined method `investments'" error when I utilize this code:
Create.js.erb
$("#investments-container").html("<%= escape_javascript(render :partial => 'projects/proj_investments', :formats => :html)%>");
I think what's going on here is that the Rails part has already rendered, so I am trying to utilizing objects like Project, Reward and Investment that are no longer accessible via AJAX. And maybe I need to somehow pass those objects on in rendering the partial. But I don't know how to do this exactly. Or, if I am wrong conceptually, that would be good to know too!
Thanks, Mike
Why does a new rails app fail to generate due to a gem install error, asking me for a password? What's the solution?
Ignoring bcrypt-3.1.10 because its extensions are not built. Try: gem pristine bcrypt --version 3.1.10
Ignoring binding_of_caller-0.7.2 because its extensions are not built. Try: gem pristine binding_of_caller --version 0.7.2
Ignoring bcrypt-3.1.10 because its extensions are not built. Try: gem pristine bcrypt --version 3.1.10
Ignoring binding_of_caller-0.7.2 because its extensions are not built. Try: gem pristine binding_of_caller --version 0.7.2
Ignoring byebug-4.0.3 because its extensions are not built. Try: gem pristine byebug --version 4.0.3
Ignoring byebug-3.5.1 because its extensions are not built. Try: gem pristine byebug --version 3.5.1
Ignoring debug_inspector-0.0.2 because its extensions are not built. Try: gem pristine debug_inspector --version 0.0.2
Ignoring json-1.8.2 because its extensions are not built. Try: gem pristine json --version 1.8.2
Ignoring json-1.8.1 because its extensions are not built. Try: gem pristine json --version 1.8.1
Ignoring mysql2-0.3.18 because its extensions are not built. Try: gem pristine mysql2 --version 0.3.18
Ignoring mysql2-0.3.17 because its extensions are not built. Try: gem pristine mysql2 --version 0.3.17
Ignoring nokogiri-1.6.6.2 because its extensions are not built. Try: gem pristine nokogiri --version 1.6.6.2
Ignoring sqlite3-1.3.10 because its extensions are not built. Try: gem pristine sqlite3 --version 1.3.10
Ignoring unf_ext-0.0.6 because its extensions are not built. Try: gem pristine unf_ext --version 0.0.6
Your user account isn't allowed to install to the system Rubygems. You can cancel this installation and run:
bundle install --path vendor/bundle
to install the gems into ./vendor/bundle/, or you can enter your password and install the bundled gems to Rubygems using sudo.
Password:
Pundit::AuthorizationNotPerformedError
I try install pundit. But when I set up the gem I have this message.
I don't really understand. I am user.admin maybe is there a conflict? Thank you for your answer.
How to compare a date in ruby?
I am running a SQL query which returns some orders each having a date. I want to check which orders were made on current date ?
I am able to do so by :
orders = Order.find_by_sql(query).reject { |o|
today = Time.now
end_of_today = Time.local(today.year, today.month, today.day, 23, 59, 59)
start_of_today = Time.local(today.year, today.month, today.day, 00,00,00 )
o.date > end_of_today
o.date < start_of_today
}.sort_by { |o|
o.delivery_date
}
'orders' contain all the orders which were made at any time Today.
Is there a simpler way of doing this in ruby ?
How to use .html_safe with || operator
I have the following piece of view code in my HAML template:
= yield(:great_view) || '<meta name="my-app" content="app-id=123, affiliate-data=, app-argument=">'
and adding .html_safe
to the second operand doesn't display it correctly, but still escapes it. What am I doing wrong? Adding parentheses around both and writing ( .. || .. ).html-safe
doesn't work either.
How to create booking according to its pitch?
I have a model pitch where i am fetching grounddetail_id. I want to show all the pitch availabe in the ground. How i can show and book pitch of ground..
grounddetails_controller.rb
class GrounddetailsController < ApplicationController
before_action :find_ground, only: [:show, :edit, :destroy, :update]
def index
@grounddetails = Grounddetail.all.order('created_at DESC')
end
def new
@grounddetail = Grounddetail.new
end
def edit
end
def show
end
def create
@grounddetail = Grounddetail.new(ground_params)
if @grounddetail.save
redirect_to @grounddetail
else
render 'new'
end
end
def update
if @grounddetail.update(ground_params)
redirect_to @grounddetail
else
render 'edit'
end
end
def destroy
@grounddetail.destroy
redirect_to root_path
end
private
def find_ground
@grounddetail = Grounddetail.find(params[:id])
end
def ground_params
params.require(:grounddetail).permit(:name, :working_hours, :end_time, :address, :contact_no, :email, :number_of_grounds, :description, :featured_ground)
end
end
routes.rb
Rails.application.routes.draw do
devise_for :users
devise_for :admins
resources :features
resources :grounddetails do
resources :pitches
end
root "grounddetails#index"
end
model
grounddetail.rb
class Grounddetail < ActiveRecord::Base
has_many :pitches, dependent: :destroy
end
pitch.rb
class Pitch < ActiveRecord::Base
belongs_to :grounddetail
end
for now i just have pitch model and routes but in controller i am confused what to use. i can i book pitch of the ground. But for single ground i am able to book.
Rails Take all actions in the controllers in area
In my rails application I add an "api" area with controllers
In the route.rb file I add the area
namespace :api do
#get "dashboard/sales_rate"
end
The controllers Class:
class Api::DashboardController < Api::ApplicationController
before_filter :authenticate_user!
def user_service
render :json => {"user_id" => current_user.id}
end
The Path is: app/controllers/api/dashboard_controller
My question is if I can that the route take all action
for example /api/dashboard/user_service and I will not add for each route row on the route.rb page
/api/{controller_under_api_namespace}/{action}
Rails Test Case Use one fixture value in another Fixture
I have two fixtures files.
country.yml
KENYA:
country_code: kenya
short_code: ke
post.yml
my_post:
content: "Lorem Ipsum"
location: kenya
I am trying to use the KENYA.country_code in my_post.location. If I use
location: KENYA.country_code
It will save it as a string i.e location = "KENYA.country_code".If I use use it inside ruby tags (<% %>), it will raise an error "so such constant exist".
Rails 4 : Active record collection looping or iteration
In my rails customer controller there is an active record collection object:
1. @pay_invoices = Invoice.where(customer_id: @pay_cus_id)
#<ActiveRecord::Relation [#<Invoice id: 37, customer_id: 53, paid_amount: 960, devicemodel_id: 2, transaction_id: "6drv3s", created_at: "2016-01-04 05:29:03", updated_at: "2016-01-25 12:16:14">, #<Invoice id: 70, customer_id: 53, paid_amount: 80, devicemodel_id: 2, transaction_id: "2mr93s", created_at: "2016-01-28 09:02:43", updated_at: "2016-01-28 09:02:43">]>
Also in my controller I am using the transaction_id: column value to find out the transaction details in the Braintree payment gateway using the following Braintree API call:
@tid = @pay_invoices[0].transaction_id
@transaction = Braintree::Transaction.find(@tid)
This works fine for me, but the transaction details of the first transaction_id: from the @pay_invoices collection only can be retrieved using this code, I want to iterate through the @pay_invoices collection and each time I want to store the braintree transaction details into another collection, so that only I can display the payment details fro each transaction in my view.
How to achieve it ?
how to include css file for datepicker jquery ui in ROR
I am trying to set a date picker on a field in ruby using gem jquery-ui-rails. Here is my gemfile code
gem 'rails', '4.2.5'
gem 'sqlite3'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'coffee-rails', '~> 4.1.0'
gem 'coffee-script-source', '~> 1.8.0'
gem 'jquery-rails', '~> 2.3.0'
gem 'turbolinks'
gem 'jbuilder', '~> 2.0'
gem 'sdoc', '~> 0.4.0', group: :doc
and this is my application.js file
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require_tree .
//= require jquery-ui
I have included a css file in application.css file of the application. which contains
*= require_tree .
*= require_self
*= require jquery.ui.all
When I click on the date picker field it displays the datepicker but no css but if in order to include the css file I use *= require jquery.ui.all
or *= require jquery-ui
then I gives an error that whhich is File not found. I have tried server restarting and everything else that was given in other posts on stack overflow but I didn't understand where I am lacking. I actually want to add the css file of datepicker. I have wasted a lot of time in doing this. Any help would be appreciated...
mercredi 27 janvier 2016
rails 4 justifiedGallery script only load the latest post with images
When i create a new post with images it works, but when i create a new post with images, justifiedGallery doesnt apply the jquery script to the previous post, why?
jQuery -> //when dom is ready
$("#userindex").justifiedGallery(
lastRow : 'justify',
captions: false,
randomize: false,
rowHeight: 80,
)
View to render post with image
<div id="userindex">
<% img.each do |link| %>
<div>
<%= image_tag(link) %>
</div>
<% end %>
</div>
Rails sanitize method replaces single quotes with double quotes
The rails sanitize method replaces single quotes with double quotes when anchor tags are seen.
Example
sanitize("<a href='https://google.com'>google</a>")
=> "<a href=\"https://google.com\">google</a>"
This is problematic because in my application, I'm sanitizing JSON payloads that can contain these strings, which causes the JSON to be malformed.
JSON.parse("{\"link\":\"<a href='https://google.com'>google</a>\"}")
=> {"link"=>"<a href='https://google.com'>google</a>"}
JSON.parse(sanitize(("{\"link\":\"<a href='https://google.com'>google</a>\"}"))
=> JSON::ParseError
I don't have any control over the input string. Is there any way to prevent the conversion of single to double quotes?
How to configure adminlte2-rails gem into rails project
I need to know, how I can to define the Available AdminLTE Options in adminlte2-rails gem. When I put the template into my project without the gem, I find easy the js file options, but with the gem I missing. Please somebody help me.
How to work with tabbed signup/signin form using devise in rails
I am a new to the whole rails environment and learning to implement 'devise' gem for my project. Currently I have a tabbed signup/signin form.
I have generated the devise views and modified the /app/views/devise/sessions/new.html.erb
to show this kind of tabbed form.Now functionality wise everything working fine. But there are several issues.
- When I am hitting http://localhost:3000/users/sign_up it still shows the devise old signup form. I want to show the same form with the
Registration
tab activated. - On the
Register
tab if I submit the form with some error (Empty Email/Password), it is again redirecting to the default device registration form to show up the error messages.
I just want to get rid of this default registration page and want to use my Register
tab for all signup purposes.
This question may sounds very basic, but I have no idea how to customize it. Please help.
in rails erb file i want to display an output as a decimal only at one place where actually it is showing as a float value
<div class='summary' align="justify" style='vertical-align: top;'>
<div>
{{:stats.tot_fte}} Employees Assigned
  {{:stats.tot_fte_effort}} Total Effort
</div>
<div>
{{:stats.tot_users}} Users Assigned
    {{:stats.tot_user_effort}} Total Effort
</div>
</div>
this is the code which i wrote to display total effort as output where i calculate total effort at some other place,where it should always be float value as i use it for other calculations.But while displaying this here i want it to be a decimal value with two numbers after the decimal.please help me in completing this as i am a beginner. The output is as follows,
340 Employees Assigned 340.89666666666665 Total Effort
453 Users Assigned 452.6066666666666 Total Effort
i want the total effort display as a decimal value only here.
Ruby on Rails - custom PATCH action for form_for
I'm working on a Spree e-commerce store built on Ruby on Rails and want a custom action where a user can mark their order as complete straight from the checkout page without going through delivery etc. I've overridden all the checkout steps but cannot get the 'Checkout' button to complete the order by sending the order to a custom action in the Orders controller.
I'd like to think I've ticked off all the boxes: created a patch action in routes.rb and checked rake routes to make sure the route exists. But it's still telling me there is no route.
The cart page won't even load before I submit anything, with the following error. I've spent all day trying to fix this so any ideas would be great....
The error:
No route matches {:action=>"complete", :controller=>"spree/orders", :method=>:patch}
Routes.rb:
resources :orders do
member do
patch 'complete', to: 'orders#complete'
end
end
Rake routes:
Prefix Verb URI Pattern Controller#Action
spree / Spree::Core::Engine
complete_order PATCH /orders/:id/complete(.:format) orders#complete
orders GET /orders(.:format) orders#index
POST /orders(.:format) orders#create
new_order GET /orders/new(.:format) orders#new
edit_order GET /orders/:id/edit(.:format) orders#edit
order GET /orders/:id(.:format) orders#show
PATCH /orders/:id(.:format) orders#update
PUT /orders/:id(.:format) orders#update
DELETE /orders/:id(.:format) orders#destroy
HTML:
<%= form_for :order, url: {action: 'complete', method: :patch} do |f| %>
<% f.submit %>
<% end %>
I haven't created the controller yet but it would be:
def complete
# mark order as complete
# redirect to confirmation page
end
Would really appreciate any help. Thanks
ruby on rails drawing failed(interesting topic!)
in the below code, i am trying to draw bunch of chart. My database has the model Person which have the attribute of "name,weight,height,color,age" So my objective is to draw the chart for each row, with weight as the x-axis, height as the y-axis. And color would be the actually color for the each chart, for eg person 1 have color yellow, then the chart should be yellow (this is very tricky to implmented)
Anyway, i am using the lazy_high_chart to implement this, but with no luck, i failed with no error, lol, error just showing: The page isn't redirecting properly Firefox has detected that the server is redirecting the request for this address in a way that will never complete.This problem can sometimes be caused by disabling or refusing to accept cookies.
But to be consistent, here comes my code: people_controller.rb
class PeopleController < ApplicationController
#GET /people/index
#GET /people
def index
@people = Person.all
end
#GET /people/show/id
def show
@person = Person.find(params[:id])
end
#GET /people/new
def new
@person = Person.new
end
#POST /people/update
def create
@person = Person.new(person_params)
@person.save
redirect_to :action => :index
end
#GET /people/edit/:id
def edit
@person = Person.find(params[:id])
end
#POST /people/update/:id
def update
@person = Person.find(params[:id])
@person.update(person_params)
redirect_to :action => :show, :id => @person
end
#GET /people/destroy/:id
def destroy
@person = Person.find(params[:id])
@person.destroy
redirect_to :action => :index
end
def display
@people = Person.all
names = []
weights = []
heights = []
colors = []
ages = []
@people.each do |x|
names = x.name
weights = x.weight
heights = x.height
colors = x.color
ages = x.age
end
@chart = LazyHighCharts::HighChart.new('graph') do |x|
x.title(:text => "Display Data")
x.xAxis(:categories => weights, :title => names, :margin => 10)
x.yAxis(:categories => heights)
x.series(:type => 'column', :name => 'showing data', :data => weights, :color => colors)
end
redirect_to :action => :display
end
private
def person_params
params.require(:person).permit(:name, :weight, :height, :color, :age)
end
end
routes.rb
Rails.application.routes.draw do
root 'people#index'
match ':controller(/:action(/:id(.:format)))', :via => :all
end
index.html.erb:
<h1> People list</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th> Weight</th>
<th> Height</th>
<th> Color</th>
<th> Age</th>
<th colspan="4"></th>
</tr>
</thead>
<tbody>
<% @people.each do |e| %>
<tr>
<td><%= e.name %></td>
<td><%= e.weight %></td>
<td><%= e.height %></td>
<td><%= e.color %></td>
<td><%= e.age %></td>
<td><%= link_to 'Show', :controller => "people", :action => "show", :id => e %></td>
<td><%= link_to 'Edit', :controller => "people", :action => "edit", :id => e %></td>
<td><%= link_to 'Delete', :controller => "people", :action => "destroy", :id => e %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Input', :controller => 'people', :action => 'new' %>
<%= link_to 'Display', :controller => "people", :action => "display" %>
display.html.erb:
<h1> Display Result</h1>
<%= high_chart("display_res", @chart) %>
I believe my routes are correct, it should be deal with the display action within the controller code block. I have read through the lazy_high_chart example, but seems too simple and not related to my case. Any ideas? many thanks
syntax error at or near "{" using rails in postgresql
Below query is working in Mysql,but its not working in postgresql.
Campaign.scheduled_with_community_ids(community_ids).
joins(:community).
order('FIELD(campaigns.id, #{editable_ids}) DESC').
order(:launch_date, 'communities.community_name')
am getting below error
ActiveRecord::StatementInvalid - PG::SyntaxError: ERROR: syntax error at or near "{" LINE 2: ...s" = 's_approved')) ORDER BY FIELD(campaigns.id, #{editable_...
Please anyone help me
mardi 26 janvier 2016
ruby on rails new method failed not show
below is my code, but my problem is in my _form.html.erb, when i use the form_for method for one of my method update, it works, but when i want to create a new data, it failed.
home controller
class HomeController < ApplicationController
def index
@inputs = Person.all
end
def new
@input = Person.new
end
def create
@input = Person.new(input_params)
respond_to do |x|
if @input.save
x.html {redirect_to :action => 'index'}
else
x.html {render :action => 'new'}
end
end
end
def show
@input = Person.find(params[:id])
end
def edit
@input = Person.find(params[:id])
end
def update
@input = Person.find(params[:id])
respond_to do |x|
if @input.update(input_params)
x.html {redirect_to :action => 'index'}
else
x.html {render :edit}
end
end
end
def destroy
@input = Person.find(params[:id])
@input.destroy
respond_to do |x|
x.html {redirect_to :action => 'index', notice: 'data was delete successfully'}
end
end
private
def input_params
params.require(:person).permit(:name, :weight, :height, :color, :age)
end
end
_form.html.erb
<%= form_for @input, url: {:action => "update"} do |person| %>
<div class="field">
<%= person.label :name %><br>
<%= person.text_field :name %>
</div>
<div class="field">
<%= person.label :weight %><br>
<%= person.number_field :weight %>
</div>
<div class="field">
<%= person.label :height %><br>
<%= person.number_field :height %>
</div>
<div class="field">
<%= person.label :color %><br>
<%= person.text_field :color %>
</div>
<div class="field">
<%= person.label :age %><br>
<%= person.number_field :age %>
</div>
<div class="actions">
<%= person.submit %>
</div>
<% end %>
routes.rb
resources:home
root 'home#index'
index.html.erb:
<p id="notice"><%= notice %></p>
<h1>Listing</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th> Weight</th>
<th> Height</th>
<th> Color</th>
<th> Age</th>
<th colspan="4"></th>
</tr>
</thead>
<tbody>
<% @inputs.each do |person| %>
<tr>
<td><%= person.name %></td>
<td><%= person.weight %></td>
<td><%= person.height %></td>
<td><%= person.color %></td>
<td><%= person.age %></td>
<td><%= link_to 'Show',home_path(person.id) %></td>
<td><%= link_to 'Edit', edit_home_path(person.id) %></td>
<td><%= link_to 'Destroy', home_path(person.id), method: :delete, data: {action: 'are you sure?'} %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Test', new_home_path %>
and lastly a screenshot of what the error is:
It has no problem when i click on 'Edit' and the 'Update'
Porting from Rails 3.2 to Rails 4.2 - Devise - registration controller bypasses validations
I have mostly ported my application from Rails 3.2 to Rails 4.2. (about 2 out of 700 tests are still failing).
In the previous Rails stack, I used:
- Rails 3.2.18
- Ruby 2.1.5
- Devise 3.2.2
- RSpec 2.13.1
Now I'm using
- Rails 4.2.5
- Ruby 2.2.4
- Devise 3.5.3
- RSpec 2.14.1
My user class looks like this:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :confirmable , :validatable
attr_accessible :name, :email, :password, :password_confirmation, :identity_url,
:remember_me, :terms
validates :terms, acceptance: { accept: 'yes' }
end
My registrations controller looks like this:
class RegistrationsController < Devise::RegistrationsController
def new
@title = "Sign up"
super
end
end
I have an RSpec test for the registrations controller which looks like this:
describe "failure to accept terms" do
before(:each) do
@attr = { :name => "New User", :email => "user@example.com",
:password => "foobar", :password_confirmation => "foobar", :terms => "no" }
end
it "should not create a user" do
lambda do
@request.env["devise.mapping"] = Devise.mappings[:user]
post :create, :user => @attr
end.should_not change(User, :count)
#raise Exception, User.last.inspect
end
end
With the previous application stack, the test passed. With the new application stack it fails.
1) RegistrationsController POST 'create' failure to accept terms should not create a user
Failure/Error: lambda do
count should not have changed, but did change from 0 to 1
With the old stack or the new stack, if I try the following in the Rails console,
irb(main) > User.all.count
=> 0
irb(main) > @attr = { :name => "New User", :email => "user@example.com", :password => "foobar", :password_confirmation => "foobar", :terms => "no" }
irb(main) > u = User.create(@attr)
irb(main) User.all.count
=> 0
irb(main) u.errors.messages
=> {:terms=>["must be accepted"]}
......the user is not created, and u.errors yields the validation error for the terms. This is what should happen.
When I uncomment the "raise Exception" line in the test, I get the following:
#<User id: 2, name: nil, email: "user@eexample.com", created_at: "2016-01-22 18:13:35", updated_at: "2016-01-22 18:13:35", encrypted_password: "$2a$04$oySRVGtQQrbKkp9hmvHlIuA8kdpEASMkhnQ4rDuDC9L...", salt: nil, admin: false, reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, confirmation_token: "_deYRJswq4yLLNrNNRAz", confirmed_at: nil, confirmation_sent_at: "2016-01-22 18:13:36", authentication_token: nil, unconfirmed_email: nil, terms: nil, identity_url: nil >
It looks like the user gets created, but key data such as the name, and terms are not assigned.
The long and the short? With Devise, user validations all ran with the Rails 3.2 stack, and did not run with the Rails 4.2 stack.
Is there a way to ensure that validations are run when using the Devise-based registrations controller?
Skip first occurrence of semi colon using regex
I am trying to skip the first semi colon in the string that looks like the one below and do a spilt on the rest of the semi colon using a regular expression
My string looks something like this
lines = </li> <li> Urinary tract infection </li> <li> Respiratory infection </li> <li> Sinus problems; and </li> <li> Ear infections; <li> Some more info </li>
I am using the below ruby code to do split this at every semi colon except the first one
lines.split(/(?<!\\\\);/)
My expected output is
["</li> <li> Urinary tract infection </li> <li> Respiratory infection </li> <li> Sinus problems; and </li> <li> Ear infections","<li> Some more info </li>" ]
Note that the string could be long with any number of semi colons but I want to prevent the splitting happening only from the first semi colon. I would appreciate some help here if keep the first occurrence of the semi colon intact.
Selecting a group collection of objects in Rails via coffeescript
I have an old Rails 3.2.22 app I'm maintaining and I'm running into a problem with creating a call
object (model) and assigning a facility (model) by region (model).
Here is a breakdown of my models, they have been minimized to show the associations and important methods.
call.rb
class Call < ActiveRecord::Base
belongs_to :transferred_from, :foreign_key => :transfer_from_id, :class_name => 'Facility'
belongs_to :transferred_to, :foreign_key => :transfer_to_id, :class_name => 'Facility'
belongs_to :region
end
region.rb
class Region < ActiveRecord::Base
attr_accessible :area
has_many :calls
has_many :facility_regions
has_many :facilities, through: :facility_regions
def active_facilities
self.facilities.active
end
end
facility.rb
class Facility < ActiveRecord::Base
has_many :calls_transferred_from, :foreign_key => :transfer_from_id, :class_name => 'Call'
has_many :calls_transferred_to, :foreign_key => :transfer_to_id, :class_name => 'Call'
has_many :facility_regions
has_many :regions, through: :facility_regions
end
When creating a call there is a list of regions which you can select one, and using coffee script it will only show the facilities which belong to that region using group collection select. Here is the excerpt from my _form.html.erb
<%= f.label :region %>
<%= f.collection_select(:region_id, Region.order("area asc"), :id, :area, {:include_blank => true}, {:class => 'select'}) %></br>
<%= f.label :Transfer_From %>
<%= f.grouped_collection_select :transfer_from_id, Region.order(:area), :active_facilities, :area, :id, :facility_name_with_facility_address, {include_blank: true}, class: 'select' %><div id ="transfer-from-address"></div></br>
So the way it should work is a call is being filled out, a region selected (ie Houston), and the coffeescript changes the list of facilities based on the input of the region. So houston will show all houston facilities dallas will show all of dallas, etc etc. If you look at the group collection select I pass a method active_facilities
which is in the region model which scopes all facilities belonging to the region and that are marked as active.
Here is the coffeescript I wrote
jQuery ->
facilities = $('#call_transfer_from_id').html()
update_facilities = ->
region = $('#call_region_id :selected').text()
options = $(facilities).filter("optgroup[label=#{region}]").html()
if options
# Set the options and include a blank option at the top
$('#call_transfer_from_id').html("<option value=''></option>" + options)
# Ensure that the blank option is selected
$('#call_transfer_from_id').attr("selected", "selected")
else
$('#call_transfer_from_id').empty()
$('#call_region_id').change ->
update_facilities()
update_facilities()
I've added a new region "Test" and assigned 3 facilities to it. But whenever I go to pull up that region "Test" it doesn't show the 3 facilities belonging to it but instead shows another region's facilities. This seems to be isolated to the new region only. I've tested assigning multiple regions to several facilities and when I create a call and select the proper region, those new facilities that were assigned to the region are scoped properly.
I went into the console and ran the following to make sure it's not an activerecord or association issue:
Region.last.active_facilities.count
and received a count of 3 which is correct for the test region I built.
I'm not sure what the problem is here, I'm thinking it may be something with the coffeescript but am not 100% sure.
I'm sorry in advance if my question is fragmented or not clear. If you need any further code examples or explanation please feel free to ask.
Rails caracal embedded image cannot be displayed
I have an issue with displaying images. This works:
docx.img 'http://ift.tt/1Pi8QDM', width: 200, height: 60
however this doesn't:
docx.img 'app/assets/images/logo.gif', width: 200, height: 60
The path is recognised, and the doc is generated, but the image is displayed in the doc with a cross and "This image cannot currently be displayed."
I asked the caracal owner on Github, who says:
Word documents embed images inside them and keep a sort of index of those assets.
When you provide an external url, Caracal uses Net::HTTP to read the data, save its data to a file, and index the embedded file via the supplied URL.
If you want to use a local file, you can do that, too, but the options signature is a bit different. Since Caracal can't use Net::HTTP to read the local file data, you'll need to do that yourself and pass Caracal the base64 data explicitly. You can use ruby's built-in File library to read the image content into a string and then use the Base64 library to encode the raw string into format that can be written into Caracal's ZIP file. As the README notes, you still want to provide the local path to the file in the img call, as this gives Caracal something to use when it indexes the resulting embedded file.
Without testing this pseudo-code at all, you'll want to do something like the following:
img_data = Base64.encode64( File.read('public/logo.png') )
docx.img 'public/logo.png' do
data img_data
width 200
height 60
end
However I still get the same issue when I do this. Anyone got any ideas?
Thanks!
Omar
Rails Converting a has_many relationship into a has and belongs to many
I have a Rails app with the following relationship:
region.rb
class Region < ActiveRecord::Base
has_many :facilities
end
facility.rb
class Facility < ActiveRecord::Base
belongs_to :region
end
I want to expand functionality a bit so that facilities can belong to more than one region at a time. I believe I can do this with a has_many_through relationship but I'm needing some guidance on converting the existing has_many into a has many through. I understand how to create and wire up the join table, but how would I take existing data and translate it?
So for instance. On a facility object there is region_id
, since the facilities can belong to more than one region I'd probably need a region_ids
field and shovel the collection of regions into that column which should then populate the other side of the association via the join table. I have this part pretty much figured out as far as moving forward and wiring up the association. But I'm unsure as to how to take existing data and translate it over so the app doesn't break when I change the model association.
Any advice would be greatly appreciated.
Rails (+ devise) + Native-React + FBSDK
I need to authenticate a User on my rails backend.
Originaly, I use Devise/Omniauth + standard FB login pattern. It works very well and I am able to authenticate a new or existing user, to create its session and so to get the devise "current_user" set up with all his FB parameters.
But I am transfering the front part into a React-Native App. I still want to login the user, but, I not only need to save the FB session cookie in the Apps but also to recognize my user on the rails server side.
I was wondering how to do.
I can easily login through the FBSDK with
I can also easily login on my rails backed with
But I need do have FB authenticating my user on my rails backend.
Any ideas how to do ?
Gracefully and Patiently reboot a server
I have an application that performs many automatic tasks, in chain and sometimes I break the chain by performing a reboot and need to mannually fix the mess.
Is there any way to check if there are running processes called by controllers / models and only perform the reboot after those are finished?
Thanks
delayed job - RES keep growing
I have some tasks which needs to rub in background so i was planning to use delayedjob gem but before put in development, i wanted to rub simple TEST to see RES consumption.
Simple Helper with no code
module TestjobHelper
def self.imageprocess(gb)
gb = nil
end
end
Putting into delay job
TestjobHelper.delay(:queue => 'testjob').imageprocess('gb')
Running Delayed Job queue command
RAILS_ENV=development script/delayed_job -i testjob --queue=testjob start
Above sample program, gives keep growing RES value even if there is nothing to do in delayed job function.
RES Output:
Ruby On Rails Basic Show method failed
My home_controller.rb
class HomeController < ApplicationController
def index
@inputs = Person.all
end
def new
@input = Person.new
end
def create
@input = Person.new(input_params)
respond_to do |x|
if @input.save
x.html {redirect_to :action => 'index'}
else
x.html {render :action => 'new'}
end
end
end
def show
@input = Person.find(params[:id])
end
private
def input_params
params.require(:inputs).permit(:name, :weight, :height, :color, :age)
end
end
My routes file only have two lines:
resources: home
root 'home#index'
My index.html.erb
<p id="notice"><%= notice %></p>
<h1>Listing</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th> Weight</th>
<th> Height</th>
<th> Color</th>
<th> Age</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @inputs.each do |person| %>
<tr>
<td><%= person.name %></td>
<td><%= person.weight %></td>
<td><%= person.height %></td>
<td><%= person.color %></td>
<td><%= person.age %></td>
<td><%= link_to 'Show',person %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
<%= link_to 'New Test', new_home_path %>
my show.html.erb:
<p>
<strong>Name:</strong>
<%= @person.name %>
</p>
<p>
<strong>Weight:</strong>
<%= @person.weight %>
</p>
<p>
<strong>Height:</strong>
<%= @person.height %>
</p>
<p>
<strong>Color:</strong>
<%= @person.color %>
</p>
<p>
<strong>Age:</strong>
<%= @person.age %>
</p>
<%= link_to 'Back', index_home_path %>
Also, here is a rake routes result from my case: enter image description here
lundi 25 janvier 2016
Accessing gem class methods in rails app
I have created my own gem 'mygem'. In the lib directory I have mygem.rb ruby file. This file has 3 methods defined.
Now I have created a rails app and I intend to use my gem in this app. In the controller ruby file I want to create a object and use the methods of my gem. But it is giving me error.
Here is the code of my controller ruby file:-
class StaticPagesController < ApplicationController
obj= Newgem.new()
def home
@message1= obj.head
@message2= obj.paraone
@message3= obj.paratwo
end
end
dimanche 24 janvier 2016
Basic Ruby: Returning a value in a string
In my teamtreehouse ruby course I am on this challenge and for some reason my solution is not clearing the challenge. What am I doing wrong
Question: In the previous challenge, we wrote a method that returned the remainder of two arguments when divided. That's cool, but it would be nicer if the method returned the remainder in a nice full sentence. Use string interpolation to return the remainder inside the sentence “The remainder of a divided by b is c.” where a is your “a” variable, b is your “b” variable, and c is the value of a % b.
My Answer
def mod(a, b)
c = a % b
puts "The remainder of #{a} divided by #{b} is #{c}"
end
Note We can only use two arguments
Errno::EACCES: Permission denied @ rb_sysopen When installing gems wtih native extensions
When I do
bundle install
on my ubuntu server. I get a permission error for all gems that uses native extensions. Like this one.
Installing json 1.8.3 with native extensions
Errno::EACCES: Permission denied @ rb_sysopen - /var/www/vhosts/my_application/httpdocs/my_application/gems/gems/json-1.8.3/tests/test_json.rb
I have installed ruby 2.2.1 with rvm and I have a local gemset for this user.
I am guessing that it might be a problem regarding the users permissions, but I don't know how to fix it.
There could also be something I need to install. Like ruby-dev?
Here are some info from the server.
rvm list
rvm rubies
=* ruby-2.2.1 [ x86_64 ]
ruby-2.2.1-dev [ x86_64 ]
ruby-2.2.4 [ x86_64 ]
# => - current
# =* - current && default
# * - default
ruby -v
ruby 2.2.1p85 (2015-02-26 revision 49769) [x86_64-linux]
bundler --version
Bundler version 1.11.2
Thanks!
undefined method `default_locale=' for nil:NilClass
I'm trying to internacionalize my application made with devise, but i'm struggling in some points. I've installe the i18n gem and created the devise.pt-BR.yml
file and wrote inside application.rb
config.i18n.default_locale = :'pt-BR'
Ok, but when i try to anything inside my application, i get the following error message:
undefined method `default_locale=' for nil:NilClass
Rails.root: /home/ubuntu/workspace/aqueleprojetoprivate/medicos Application Trace | Framework Trace | Full Trace
app/controllers/application_controller.rb:8:in
<class:ApplicationController>' app/controllers/application_controller.rb:1:in
' activesupport (4.2.4) lib/active_support/dependencies.rb:457:inload' activesupport (4.2.4) lib/active_support/dependencies.rb:457:in
block in load_file' activesupport (4.2.4) lib/active_support/dependencies.rb:647:innew_constants_in' activesupport (4.2.4) lib/active_support/dependencies.rb:456:in
load_file' activesupport (4.2.4) lib/active_support/dependencies.rb:354:inrequire_or_load' activesupport (4.2.4) lib/active_support/dependencies.rb:494:in
load_missing_constant' activesupport (4.2.4) lib/active_support/dependencies.rb:184:inconst_missing' app/controllers/home_controller.rb:1:in
' activesupport (4.2.4) lib/active_support/dependencies.rb:457:inload' activesupport (4.2.4) lib/active_support/dependencies.rb:457:in
block in load_file' activesupport (4.2.4) lib/active_support/dependencies.rb:647:innew_constants_in' activesupport (4.2.4) lib/active_support/dependencies.rb:456:in
load_file' activesupport (4.2.4) lib/active_support/dependencies.rb:354:inrequire_or_load' activesupport (4.2.4) lib/active_support/dependencies.rb:494:in
load_missing_constant' activesupport (4.2.4) lib/active_support/dependencies.rb:184:inconst_missing' activesupport (4.2.4) lib/active_support/inflector/methods.rb:261:in
const_get' activesupport (4.2.4) lib/active_support/inflector/methods.rb:261:inblock in constantize' activesupport (4.2.4) lib/active_support/inflector/methods.rb:259:in
each' activesupport (4.2.4) lib/active_support/inflector/methods.rb:259:ininject' activesupport (4.2.4) lib/active_support/inflector/methods.rb:259:in
constantize' activesupport (4.2.4) lib/active_support/dependencies.rb:566:inget' activesupport (4.2.4) lib/active_support/dependencies.rb:597:in
constantize' actionpack (4.2.4) lib/action_dispatch/routing/route_set.rb:72:incontroller_reference' actionpack (4.2.4) lib/action_dispatch/routing/route_set.rb:62:in
controller' actionpack (4.2.4) lib/action_dispatch/routing/route_set.rb:41:inserve' actionpack (4.2.4) lib/action_dispatch/journey/router.rb:43:in
block in serve' actionpack (4.2.4) lib/action_dispatch/journey/router.rb:30:ineach' actionpack (4.2.4) lib/action_dispatch/journey/router.rb:30:in
serve' actionpack (4.2.4) lib/action_dispatch/routing/route_set.rb:821:incall' warden (1.2.4) lib/warden/manager.rb:35:in
block in call' warden (1.2.4) lib/warden/manager.rb:34:incatch' warden (1.2.4) lib/warden/manager.rb:34:in
call' rack (1.6.4) lib/rack/etag.rb:24:incall' rack (1.6.4) lib/rack/conditionalget.rb:25:in
call' rack (1.6.4) lib/rack/head.rb:13:incall' actionpack (4.2.4) lib/action_dispatch/middleware/params_parser.rb:27:in
call' actionpack (4.2.4) lib/action_dispatch/middleware/flash.rb:260:incall' rack (1.6.4) lib/rack/session/abstract/id.rb:225:in
context' rack (1.6.4) lib/rack/session/abstract/id.rb:220:incall' actionpack (4.2.4) lib/action_dispatch/middleware/cookies.rb:560:in
call' activerecord (4.2.4) lib/active_record/query_cache.rb:36:incall' activerecord (4.2.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in
call' activerecord (4.2.4) lib/active_record/migration.rb:377:incall' actionpack (4.2.4) lib/action_dispatch/middleware/callbacks.rb:29:in
block in call' activesupport (4.2.4) lib/active_support/callbacks.rb:88:in__run_callbacks__' activesupport (4.2.4) lib/active_support/callbacks.rb:778:in
_run_call_callbacks' activesupport (4.2.4) lib/active_support/callbacks.rb:81:inrun_callbacks' actionpack (4.2.4) lib/action_dispatch/middleware/callbacks.rb:27:in
call' actionpack (4.2.4) lib/action_dispatch/middleware/reloader.rb:73:incall' actionpack (4.2.4) lib/action_dispatch/middleware/remote_ip.rb:78:in
call' actionpack (4.2.4) lib/action_dispatch/middleware/debug_exceptions.rb:17:incall' web-console (2.2.1) lib/web_console/middleware.rb:31:in
call' actionpack (4.2.4) lib/action_dispatch/middleware/show_exceptions.rb:30:incall' railties (4.2.4) lib/rails/rack/logger.rb:38:in
call_app' railties (4.2.4) lib/rails/rack/logger.rb:20:inblock in call' activesupport (4.2.4) lib/active_support/tagged_logging.rb:68:in
block in tagged' activesupport (4.2.4) lib/active_support/tagged_logging.rb:26:intagged' activesupport (4.2.4) lib/active_support/tagged_logging.rb:68:in
tagged' railties (4.2.4) lib/rails/rack/logger.rb:20:incall' actionpack (4.2.4) lib/action_dispatch/middleware/request_id.rb:21:in
call' rack (1.6.4) lib/rack/methodoverride.rb:22:incall' rack (1.6.4) lib/rack/runtime.rb:18:in
call' activesupport (4.2.4) lib/active_support/cache/strategy/local_cache_middleware.rb:28:incall' rack (1.6.4) lib/rack/lock.rb:17:in
call' actionpack (4.2.4) lib/action_dispatch/middleware/static.rb:116:incall' rack (1.6.4) lib/rack/sendfile.rb:113:in
call' railties (4.2.4) lib/rails/engine.rb:518:incall' railties (4.2.4) lib/rails/application.rb:165:in
call' rack (1.6.4) lib/rack/lock.rb:17:incall' rack (1.6.4) lib/rack/content_length.rb:15:in
call' rack (1.6.4) lib/rack/handler/webrick.rb:88:inservice' /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:138:in
service' /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:94:inrun' /usr/local/rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/server.rb:294:in
block in start_thread'
How do i fix it?
rails not working in ruby on rails
expertly@AECUTE ~/Documents/RUBY/timetable $ rails s
/home/expertly/.rvm/gems/ruby-2.2.4/gems/bundler-1.11.2/lib/bundler/runtime.rb:80:in rescue in block (2 levels) in require': There was an error while trying to load the gem 'uglifier'. (Bundler::GemRequireError) from /home/expertly/.rvm/gems/ruby-2.2.4/gems/bundler-1.11.2/lib/bundler/runtime.rb:76:in
block (2 levels) in require' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in each' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/bundler-1.11.2/lib/bundler/runtime.rb:72:in
block in require' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in each' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/bundler-1.11.2/lib/bundler/runtime.rb:61:in
require' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/bundler-1.11.2/lib/bundler.rb:99:in require' from /home/expertly/Documents/RUBY/timetable/config/application.rb:7:in
' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:78:in require' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:78:in
block in server' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:75:in tap' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:75:in
server' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/railties-4.2.5/lib/rails/commands/commands_tasks.rb:39:in run_command!' from /home/expertly/.rvm/gems/ruby-2.2.4/gems/railties-4.2.5/lib/rails/commands.rb:17:in
' from bin/rails:4:in require' from bin/rails:4:in
'
please help me for this problem.
samedi 23 janvier 2016
rails nasted model form
I have model association like this
post.rb
title:string description:text
class Post < ActiveRecord::Base
belongs_to :user
has_many :items
accepts_nested_attributes_for :items
end
item.rb
post_id:integer order:integer
class Item < ActiveRecord::Base
belongs_to :post
has_one :link
has_one :movie
has_one :photo
has_one :quate
end
link, movie, photo, quate.rb
link.rb : item_id:integer url:string url-text:string
movie.rb : item_id:integer youtube-url:string
photo.rb : item_id:integer image:string comment:string title:string
quate.rb : item_id:integer quate:string q-url:string q-title:string
belongs_to :item
I want to build user-post application by ruby on rails. Item model has order column ,so user can choose and add whatever movie, link , photo to build there own post.
How can I build form for these nasted models?
Carrierwave uploader consuming memroy
I am using Carrierwave uploader V0.10.0 for my rails project (on RHEL) to upload 310 MB of zip file to server. While file is being transferred, I could see the server's available memory is decreasing. After file gets download and when call come to the controller to save the uploaded file, I could see the deduction of 3 times (of zip file, say 930 MB) size of memory from available file system space. I am not able to figure out why its happening.
Any help is great.
How to use CanCanCan with enum field?
I got Article model with enum field enum status: [:pending, :done]
.
Here's my ability file
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new
if user.member?
can :read, Article.done
end
end
end
In view I am trying to render Article.done collection for member but nothings renders.
<% if can? :read, Article.done %>
<%= render partial: 'article', collection: Article.done, as: :article %>
<% end %>
Therefore I have a question: is there any possible way to work with enum in CanCanCan?
button_to in Rails 4 : Redirection to Controller action with params and Bootstrap Class
In my Rails 4 project, in a Customer view I want to define a button_to , to call the my_method in my customer controller. Also I want to pass some params also with bootstarp class: class: "btn btn-primary".
I tried this :
<td><%= button_to "Charge Customer",charge_lease_customer_customers_path, params: { doc_delete: true }, class: "btn btn-primary" %></td>
In my routes.rb
get 'charge_lease_customer' => 'customers#charge_lease_customer', as: :charge_lease_customer
When I click on the button the following error screen appears:
No route matches [POST] "/customers/charge_lease_customer"
How to achive it ?
Rails: will_paginate run extra SQL query when calling page_entries_info
My application using rails '3.2.20', mysql2 '0.3.20' and will_paginate '3.0.7'
I'm trying to load user records
@users = User.paginate(:page => params[:page], :per_page => 20)
Below queries executed in console
User Load (0.3ms) SELECT `users`.* FROM `users` LIMIT 20 OFFSET 0
(0.3ms) SELECT COUNT(*) FROM `users`
Generally will_paginate run two queries for collections and count
But I got one more extra query when used page_entries_info in view
User Load (0.3ms) SELECT `users`.* FROM `users` LIMIT 20 OFFSET 0
(0.3ms) SELECT COUNT(*) FROM `users`
User Load (0.2ms) SELECT `users`.* FROM `users` LIMIT 1 OFFSET 0
hope last query is not used anywhere.
I just illustrate with simple example, but my application executes large query with more joins and includes.
It may slow down the performance with unnecessary query.
This occurs only after will_paginate '3.0.3'
is it bug/functionality? how to avoid this extra query?
NameError: uninitialized constant ApplicationHelperTest::Fill_IN
I get this error message when I add the last test in this code from Ruby on Rails Tutorial, from listing 6.11 and 6.12 and then run the bundle exec rake test Listing 6.13 I am running Linux Xubuntu
1) Error: ApplicationHelperTest#test_full_title_helper: NameError: uninitialized constant ApplicationHelperTest::FILL_IN test/helpers/application_helper_test.rb:5:in `block in '
When I remove the email validation the test passes.
test/models/user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase
def setup
@user = User.new(name: "Example User", email: "user@example.com")
end
test "should be valid" do
assert @user.valid?
end
test "name should be present" do
@user.name = ""
assert_not @user.valid?
end
test "email should be present" do
@user.email = " "
assert_not @user.valid?
end
end
app/models/user.rb
class User < ActiveRecord::Base
validates :name, presence: true
validates :email, presence: true
end
I think it must have something to do with the Application Helper. this is the code in the helper:
require 'test_helper'
class ApplicationHelperTest < ActionView::TestCase
test "full title helper" do
assert_equal full_title, FILL_IN
assert_equal full_title("Help"), FILL_IN
end
end
vendredi 22 janvier 2016
Referencing multiple models in Rails
I have departments with many positions with many crewmembers. I am trying to make a page of a master list of crewmembers, grouped by their positions which are grouped by their departments. I know the code below is wrong, but hopefully someone could point me in the correct direction.
<% @departments.each do |dept| %>
<% if Department.position.include? crewmember %>
<%= dept.department %><br />
<% @positions.each do |pos| %>
<% if Position.crewmember.any? %>
<%= pos.position %><br />
<%= pos.position.crewmember %>
<% end %>
<% end %>
<% end %>
<% end %>
Different values from root_url with RSpec
I have a controller spec in which I test the responses I get from my controller. My response should have a link that is formed like so:
root_url + 'some_image.png'
That is how I form the link in the decorator.
My problem is that in my spec when I create the expected response body it gets the URL as this:
http://ift.tt/1Jrn7xu
But the actual response I get from the controller is as this:
http://ift.tt/1Jrn7xw
I think this is because the controller request stubs out the root_url
to this, but in the actual spec code it doesn't
I tried to stub the root_url
method with no luck, how I can fix this issue?
Porting from Rails 3.2 to Rails 4.2 - Devise - registration controller bypasses validations
I have mostly ported my application from Rails 3.2 to Rails 4.2. (about 2 out of 700 tests are still failing).
In the previous Rails stack, I used:
- Rails 3.2.18
- Ruby 2.1.5
- Devise 3.2.2
- RSpec 2.13.1
Now I'm using
- Rails 4.2.5
- Ruby 2.2.4
- Devise 3.5.3
- RSpec 2.14.1
My user class looks like this:
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :confirmable , :validatable
attr_accessible :name, :email, :password, :password_confirmation, :identity_url,
:remember_me, :terms
validates :terms, acceptance: { accept: 'yes' }
end
My registrations controller looks like this:
class RegistrationsController < Devise::RegistrationsController
def new
@title = "Sign up"
super
end
end
I have an RSpec test for the registrations controller which looks like this:
describe "failure to accept terms" do
before(:each) do
@attr = { :name => "New User", :email => "user@example.com",
:password => "foobar", :password_confirmation => "foobar", :terms => "no" }
end
it "should not create a user" do
lambda do
@request.env["devise.mapping"] = Devise.mappings[:user]
post :create, :user => @attr
end.should_not change(User, :count)
#raise Exception, User.last.inspect
end
end
With the previous application stack, the test passed. With the new application stack it fails.
1) RegistrationsController POST 'create' failure to accept terms should not create a user
Failure/Error: lambda do
count should not have changed, but did change from 0 to 1
With the old stack or the new stack, if I try the following in the Rails console,
irb(main) > User.all.count
=> 0
irb(main) > @attr = { :name => "New User", :email => "user@example.com", :password => "foobar", :password_confirmation => "foobar", :terms => "no" }
irb(main) > u = User.create(@attr)
irb(main) User.all.count
=> 0
irb(main) u.errors.messages
=> {:terms=>["must be accepted"]}
......the user is not created, and u.errors yields the validation error for the terms. This is what should happen.
When I uncomment the "raise Exception" line in the test, I get the following:
#<User id: 2, name: nil, email: "user@eexample.com", created_at: "2016-01-22 18:13:35", updated_at: "2016-01-22 18:13:35", encrypted_password: "$2a$04$oySRVGtQQrbKkp9hmvHlIuA8kdpEASMkhnQ4rDuDC9L...", salt: nil, admin: false, reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, confirmation_token: "_deYRJswq4yLLNrNNRAz", confirmed_at: nil, confirmation_sent_at: "2016-01-22 18:13:36", authentication_token: nil, unconfirmed_email: nil, terms: nil, identity_url: nil >
It looks like the user gets created, but key data such as the name, and terms are not assigned.
The long and the short? With Devise, user validations all ran with the Rails 3.2 stack, and did not run with the Rails 4.2 stack.
Is there a way to ensure that validations are run when using the Devise-based registrations controller?
Do 'starts_with' and 'start_with' have the same function in Ruby?
Apparently they are giving me the same output on any input like
"Ruby is red".start_with?"Ruby"
or
"Ruby is red".starts_with?"Ruby"
both are giving the same result.
Time Format-Activeadmin
I'm using time data type in my model, I used open_time.strftime('%I:%M:%S:%p') to save the time, But I got a problem while retrieving the data from model using "Rest Client Api" it returns the time data as "open_time": "2000-01-01T05:02:00+05:30" instead of HH:MM:SS format. Need help!
using wiked_pdf how to add the page number to the footer of each page in ruby on rails
how can i add the page number at the footer of each page without using JavaScript.But in controller i given like this
format.pdf do
f = SentSurvey.generate_pdf_report(sent_survey_skope.pluck(:id), report_type)
send_file f, type: :pdf, filename: report_filename, :footer => { :right => '[1] of [topage]' }
end
like this i added but its not giving the page number
or
<script>
function number_pages() {
var vars={};
var x=document.location.search.substring(1).split('&');
for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = decodeURIComponent(z[1]);}
var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];
for(var i in x) {
var y = document.getElementsByClassName(x[i]);
for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];
}
}
</script>
<body onload="number_pages()">
Page <span class="page"></span> of <span class="topage"></span>
</body>
This is also not helping to me..
jeudi 21 janvier 2016
Warden - default Encryption strategy it uses?
Can someone tell me the default encryption strategy the Warden gem (http://ift.tt/1bfyaZI) uses to encrypt password?
How to implement authorization?
Suppose, I have a model called Animal. This model contains enum attribute kind with two possible states.
class Animal < ActiveRecord::Base
enum kind: [ :cat, :dog ]
end
Then in my controller I create different instance variables.
class AnimalsController < ApplicationController
def index
@cats = Animal.cat
@dogs = Animal.dog
end
end
In my view I got two separate collections.
<h1>Animals</h1>
<%= render partial: 'animals/cat', collection: @cats, as: :cat %>
<%= render partial: 'animals/dog', collection: @dogs, as: :dog %>
How can I make an authorization to be able to edit the first collection's resources and not to be able to edit the second ones?
The following approach won't work because it works only for one action entirely.
before_action :current_user_only, except: [:edit]
So, how do I implement that kind of authorization?
Thanks in advance!
how is the scoping stack in RAILS 3.2 handled? I have a nice idea how to override a default scope, but really get stuck with active records logic.
Pre 0: I post 2 questions with almost the same intro here, but the requested/expected answers are very different
(other question is my solution ok?)
Pre: my question belongs to Rails 3.2 & plz. I don't want to discuss using default_scope at all; I know, that there are a lot of arguments not to use it (in wrong way)
I have the 'classical' soft delete records problem that is - as I think - almost perfectly solved with a default_scope, in my case the soft delete is for undo reasons. But I do not want to use unscope or plain sql if I need to access a deleted record
My Idea is just easy: since (where) scopes are just "and-ed", it does not make sense to have a default_scope where("deleted=false")
and an other scope where("deleted in [true, false]")
What we get as SQL is something like
where deleted=false and deleted in (true, false)
so the next step is to look in previous "where" scopes before sending the last requested default_scope
if there is a "deleted=all" in where scopes, I send a "where 1=1" default_scope, if not, I send default a where "deleted = false" default_scope
But what ever I try, I can only see the where scopes in debugger, I can not find a way to look what scopes are already used from inside my Toast model.
So - imagine - I want to make a "puts" printing the scope chain for something like that:
Toast.not_to_dark.not_to_light.with_butter....
and Toast scopes
scope :not_to_dark
where black < 80
scope :not_to_light
where black > 20
scope :with_butter
where butter=true
It should be possible to collect that information when the "with_butter" scope is executed, but what ever I try, I fail, it feels like RAILS does not want me to get access to that information.
where is it how to get it?
Is my "override default_scope" solution for rails 3.2(!) ok? or if not why not?
Pre 0: I post 2 questions with almost the same intro here, but the requested/expected answers are very different
Pre: my question belongs to Rails 3.2 & plz. I don't want to discuss using default_scope
at all; I know, that there are a lot of arguments not to use it (in wrong way)
I have the 'classical' soft delete records problem that is - as I think - almost perfectly solved with a default_scope
, in my case the soft delete is for undo reasons. But I do not want to use unscope
or plain sql if I need to access a deleted record
Since my first attempt (link-after question schedule), to search the scopes already used, did not work, I found this solution that seems to work nice, but it is so easy, that I am not sure; I don't feel like a Rails "hacker"
Based on the sources and a hand full of debugging, I learned that the default_scope is resolved after all others, so the idea was just to make a dynamic default_scope
based on this:
# If you need to do more complex things with a default scope, you can alternatively # define it as a class method: # # class Article < ActiveRecord::Base # def self.default_scope # # Should return a scope, you can call 'super' here etc. # end # end
in default.rb
, I felt brave and tried following:
I have only a group of "soft delete candidates" in my models, and I want to handle them all the same way, i introduced a SoftDelRecord
- module, that I include SoftDelRecord
in all models, that are part.
The idea: "turn off default scope if a 'use all' scope was used before", so that i can use:
Toast.where(brownstate: 'fine') # default scope ON
or
Toast.include_deleted.where(brownstate: 'fine') # default scope OFF
and all other scoped variants I tried
module SoftDelRecord
def self.included base
base.extend ClassMethods
end
module ClassMethods
def default_scope
if clr_default_scope
set_clr_default_scope(false)
where('')
else
where('active = true')
end
end
def include_deleted
set_clr_default_scope('true')
where('')
end
def clr_default_scope
Thread.current["#{self}_sdr_include_deleted"]
end
def set_clr_default_scope(tf)
Thread.current["#{self}_sdr_include_deleted"]=tf
end
end
end
It's some how to easy, to believe, but all I tried works, or seems to work.
what have I overseen?
Rails - Updating product actually destroys it
I am new to Rails and was creating a demo web shop app for study. I could create the products smoothly, both via rails console and by the url localhost:300/products/new. My problem is when I want to update them. I have _form.html.erb partial getting rendered both in new.html.erb and edit.html.erb
In /products/id/edit though the button "Update Product" is actually destroying the product instead of updating it
This is the _form.htlm.erb:
<%= form_for(@product) do |f| %>
<% if @product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% @product.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="row">
<div class="col-sm-4 col-xs-12">
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name, :class => "input-group input-group-sm" %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :image_url %><br>
<%= f.text_field :image_url %>
</div>
<div class="field">
<%= f.label :color %><br>
<%= f.text_field :color %>
</div>
<div class="actions">
<%= f.submit %>
</div>
</div>
</div>
Please tell me if you need more data Thanks, Anna
Use Ruby on Rails in Javascript script
I try to create my own SonarQube Widget and I have the following question ? I want to save in a javascript variable the result of my Metrics. The problem is that I don't succeed to use Ruby on Rails with Javascript.
<script type="text/javascript">
var text = "<%= format_measure('sonar.metric.arcadsoftware.rpg.ruleset1') %>";
alert(text);
</script>
If I use just <p><%= format_measure('sonar.metric.arcadsoftware.rpg.ruleset1') -%> </p>
the result is "True" on my widget. So I want to store the String 'True' in my javascript variable text.
Thank you
How to do upload+send images to email in rails3
i have integrated image upload feature in rails3 app through gem 'paperclip', '~> 4.2', '>= 4.2.3'. And now i am looking for sending that image on email addresses.
RAILS how to get projects from the projectmemberships model into the jBUILDER file
i am making an api. i have 3 models the users the projects and the projectmemberships with associations of:
user.rb
- has_many :projects, dependent: :destroy
- has_many :projectmemberships
- has_many :membered_projectmemberships, :class_name => "projectmemberships", :foreign_key => "project_id"
- has_many :membered_projects, :through => :membered_projectmemberships, :source => :project
project.rb
- belongs_to :user
- has_many :pmembers, :through => :projectmemberships
projectmembership.rb
- belongs_to :user
- belongs_to :project, :class_name => "Project"
- belongs_to :pmember, :class_name => "User"
i could get users membered to a project through the pmembers in the show.jbuilder
json.pmembers @project.pmembers, :id,:name
but now i dont know how to get the projects the users is membered to i try to follow the tutorial of http://ift.tt/1riQTaC
but i get is a uninitialized constant User::projectmemberships
when i try json.membered_projects @user.membered_projects, :id, :name
Rspec Rake Task: How to parse a parameter?
I have a rake task which generates a new User. Values of email, password and password_confirmation (confirm) needs to be typed in through the command line.
This is my rake task code:
namespace :db do
namespace :setup do
desc "Create Admin User"
task :admin => :environment do
ui = HighLine.new
email = ui.ask("Email: ")
password = ui.ask("Enter password: ") { |q| q.echo = false }
confirm = ui.ask("Confirm password: ") { |q| q.echo = false }
user = User.new(email: email, password: password,
password_confirmation: confirm)
if user.save
puts "User account created."
else
puts
puts "Problem creating user account:"
puts user.errors.full_messages
end
end
end
end
I can call this by typing "rake db:setup:admin" from my command line.
Now I want to test this task with a rspec. So far I managed to create the following spec file:
require 'spec_helper'
require 'rake'
describe "rake task setup:admin" do
before do
load File.expand_path("../../../lib/tasks/setup.rake", __FILE__)
Rake::Task.define_task(:environment)
end
let :run_rake_task do
Rake.application["db:setup:admin"].invoke(email: "hi")
end
it "creates a new User" do
run_rake_task
end
end
While running the specs the of my rake task will ask for input from my command line. So what I need is to parse a value for email, password and confirm so that when executing my specs the rake task won't ask for a value of those fields.
How can I achieve this from the spec file?
Rails 4 : Table Boolean Column Update Using "link_to "with a specific value "TRUE" always
In my customer controller the update method code is like bellow:
def update
@customer= Customer.find(params[:id])
if @customer.update_attributes(customer_params)
redirect_to customers_path
else
render 'edit'
end
end
In my view in customers index page I am planning to add a "link_to" link, if it is clicked, then that particular customers field "doc_delete" should be updated with value "TRUE".
<td><%= link_to "[Update", *************what is here ?******** method: :put %></td>
any one help me, getting error with my rails server when i adding authentication
Couldn't find User with 'id'=8
Extracted source (around line #13): def current_user 13@current_user ||= User.find(session[:user_id]) if session[:user_id] 14end 15 16 def require_user
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def require_user
Rails.root: C:/Users/AB COMPUTER/SecureSite
Application Trace | Framework Trace | Full Trace app/controllers/application_controller.rb:13:in current_user' app/controllers/application_controller.rb:17:in
require_user' Request
mercredi 20 janvier 2016
NameError: uninitialized constant ApplicationHelperTest::Fill_IN
I am new to programming. I get this error message when I add the last test in this code from Ruby on Rails Tutorial, from listing 6.11 and 6.12 and then run the bundle exec rake test Listing 6.13 I am running Linux Xubuntu
1) Error: ApplicationHelperTest#test_full_title_helper: NameError: uninitialized constant ApplicationHelperTest::FILL_IN test/helpers/application_helper_test.rb:5:in `block in '
This is my code I have tried many times. When I remove the email validation the test passes.
test/models/user_test.rb
require 'test_helper'
class UserTest < ActiveSupport::TestCase def setup @user = User.new(name: "Example User", email: "user@example.com") end
test "should be valid" do assert @user.valid? end
test "name should be present" do @user.name = "" assert_not @user.valid? end
test "email should be present" do @user.email = " " assert_not @user.valid? end
end
app/models/user.rb
class User < ActiveRecord::Base validates :name, presence: true validates :email, presence: true end
I think it must have something to do with the Application Helper. this is the code in the helper:
require 'test_helper'
class ApplicationHelperTest < ActionView::TestCase
test "full title helper" do assert_equal full_title, FILL_IN assert_equal full_title("Help"), FILL_IN end end
Show values from helper method in drop down - Ruby on Rails
I am using a hash constant in my ROR application. I want to show the names
from the hash constant to drop down.
helper.rb
PRODUCE_GROWING_METHODS = [
{id: 1, name: 'Conventional'},
{id: 2, name: 'Organic'},
]
def produce_growing_methods
PRODUCE_GROWING_METHODS
end
_produce.haml
= f.simple_fields_for :produce_details do |pd|
= pd.input :produce_growing_method, :collection => produce_growing_methods.collect { |x| [x[0], x[1]] }, :prompt => "Select Growing Method"
I tried as shown above in _produce.haml
but i am getting the empty drop down. Names
from the constant are not populated in drop down.
Can any one help me how to show the names
from the PRODUCE_GROWING_METHODS
hash constant to a drop down.
Thanks
mardi 19 janvier 2016
How to render different collections at the same place?
Suppose, I have a model called Animal. This model contains enum attribute kind with two possible states.
class Animal < ActiveRecord::Base
enum kind: [ :cat, :dog ]
end
Then in my controller I create corresponding instance variables collections.
class AnimalsController < ApplicationController
def index
@cats = Animal.cat
@dogs = Animal.dog
end
end
In my view I got two links and two collections.
<h1>Animals</h1>
<b><%= link_to 'List Cats' %></b>
<b><%= link_to 'List Dogs' %></b>
<%= render partial: 'animals/cat', collection: @cats, as: :cat %>
<%= render partial: 'animals/dog', collection: @dogs, as: :dog %>
What is the prefered way of displaying first collection instead of second or second one instead of the first in the same place depending on clicked link? How to do that?
Ruby on Rails with external database, issues with web requests
I need to use Ruby on Rails with an external Postgres database. I have hooked up models to the database, and can run searches to the database using calls like Model.all. However, when I try and do a web request of the same data, I get the following error:
Started GET "/v1/products" for 127.0.0.1 at 2016-01-19 22:53:34 -0800
ActiveRecord::PendingMigrationError (
Migrations are pending. To resolve this issue, run:
bin/rake db:migrate RAILS_ENV=development
):
I am an amateur Rails and database user, so I'm not sure what exactly a migrate does, but I do not have write permissions, so I cannot run one.
So, what can I do to the Rails project such that I can complete these web requests without needing to perform a migration? Any help is greatly appreciated!
Hash, Keys & Parameters
I am using this crazy cart api (that I must use) to pull product information. I need to store (Name, Price & short description) and pull that information on the fly.
All that I can seem to complete is:
@product_card = Hash.new(0)
products.each do |product|
@product_card[product['name']] = @product_card[product['name']] = client.call('call' ,session_id ,"product.info#{product[id]}")
end
<% @product_card.each do |key, value| %>
<p>Key: <%= key %></p>
<p>Value: <% value %></p>
what I would like to do is call on the @Hash.name @Hash.price @Hash.more I have been reading this all day and still can not do what I need.
I would be thankful for any help or links and this point.
Not able to verify if ga 'ec:addProduct ' is working or not. But able to see ga'ec:setAction','click' in ga debugger
= link_to designer_design_path(design.designer, design),onclick:"ga('ec:addProduct',{'id': #{design.id},'name': #{design.title},'category': #{category},'brand': #{designer.name},'price': #{design.discount_price},'quantity': #{design.quantity}}); ga('ec:setAction', 'click',{'list':#{@ga_list} })", target: '_blank'
This is the response after click
ActionController::UrlGenerationError in Users#show No route matches error
I am creating a users controller to show the users profile page but i am getting this error ActionController::UrlGenerationError in Users#show No route matches {:action=>"show", :controller=>"users", :id=>nil} missing required keys: [:id] error
I am trying to add a profile page for each user so when the user for example goes to
http://ift.tt/1RxLIDn
it will show their profile page
Here's my code:
layouts/_navbar.html.erb
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Skillbook</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
</ul>
<ul class="nav navbar-nav navbar-right">
<% if user_signed_in? %>
<td><%= link_to "Profile", user_path(current_user.username) %></td>
<td><%= gravatar_tag current_user.email, size: 20 %><%= current_user.username %></td>
<li><%= link_to "Edit user", edit_user_registration_path %></li>
<li><%= link_to "Log out", destroy_user_session_path ,method: :delete %></li>
<%else%>
<li><%= link_to "Log in", new_user_session_path %></li>
<li><%= link_to " Sign up", new_user_registration_path%></li>
<%end%>
</ul>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
users_controller.rb
class UsersController < ApplicationController
before_action :set_user, only: [:show]
private
def set_user
@user = User.find_by(username: params[:id])
end
end
routes.rb
Rails.application.routes.draw do
get 'pages/home'
devise_for :users
root 'pages#home'
resources :users, only: [:show, :index]
end