Is there any Rails command/method to list the indexes of an SQL table?
lundi 31 août 2015
having errors with localhost:3000/subjects/lists
i started this rails essential training, i am having problems with display the right output for localhost:3000/subjects/lists. instead what i am getting is "no route matches[GET] "/subjects/lists". please help me
How can I run single command on multiple servers in Ruby
How can I run single command on multiple servers in Ruby
example: I have 100 servers which has open connection from main server. I need to run the "find" command from main server to see what are the files modified for last 7 days for 100 Servers
mongrel 1.1.5 error on ruby on rails 1.8.7, 3.0.10- ubuntu 14.10
i'm having this weird error on my app, it works fine in my linux mint, but in my ubuntu it rises syntax error after installing manually the mongrel gem;
the bundle install failed in automatically install mongrel, when i ran 'gem install mongrel -v 1.1.5' mongrel installed but won't work;
here's the terminal log:
loco@DevSATO7:~/Sites/Rails/kw_nesporte$ rails s -b 192.168.1.196
/home/loco/.rvm/gems/ruby-1.8.7-head/gems/mongrel-1.1.5/lib/mongrel/handlers.rb:214: warning: else without rescue is useless
/home/loco/.rvm/gems/ruby-1.8.7-head/gems/mongrel-1.1.5/lib/mongrel.rb:22:in `require': /home/loco/.rvm/gems/ruby-1.8.7-head/gems/mongrel-1.1.5/lib/mongrel/handlers.rb:208: syntax error, unexpected ':', expecting keyword_then or ',' or ';' or '\n' (SyntaxError)
...te(modified_since) rescue nil : false
... ^
/home/loco/.rvm/gems/ruby-1.8.7-head/gems/mongrel-1.1.5/lib/mongrel/handlers.rb:209: syntax error, unexpected ':', expecting keyword_end
... : false
... ^
/home/loco/.rvm/gems/ruby-1.8.7-head/gems/mongrel-1.1.5/lib/mongrel/handlers.rb:210: syntax error, unexpected ':', expecting keyword_end
... : false
... ^
/home/loco/.rvm/gems/ruby-1.8.7-head/gems/mongrel-1.1.5/lib/mongrel/handlers.rb:211: syntax error, unexpected ':', expecting keyword_end
... : false
... ^
/home/loco/.rvm/gems/ruby-1.8.7-head/gems/mongrel-1.1.5/lib/mongrel/handlers.rb:212: syntax error, unexpected ':', expecting keyword_end
...).include?(etag) : false
... ^
/home/loco/.rvm/gems/ruby-1.8.7-head/gems/mongrel-1.1.5/lib/mongrel/handlers.rb:468: syntax error, unexpected keyword_end, expecting end-of-input
from /home/loco/.rvm/gems/ruby-1.8.7-head/gems/mongrel-1.1.5/lib/mongrel.rb:22:in `<top (required)>'
from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:76:in `require'
from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:76:in `block (2 levels) in require'
from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:72:in `each'
from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:72:in `block in require'
from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:61:in `each'
from /usr/lib/ruby/vendor_ruby/bundler/runtime.rb:61:in `require'
from /usr/lib/ruby/vendor_ruby/bundler.rb:132:in `require'
from /home/loco/Sites/Rails/kw_nesporte/config/application.rb:7:in `<top (required)>'
from /home/loco/.rvm/gems/ruby-1.8.7-head/gems/railties-3.0.10/lib/rails/commands.rb:28:in `require'
from /home/loco/.rvm/gems/ruby-1.8.7-head/gems/railties-3.0.10/lib/rails/commands.rb:28:in `block in <top (required)>'
from /home/loco/.rvm/gems/ruby-1.8.7-head/gems/railties-3.0.10/lib/rails/commands.rb:27:in `tap'
from /home/loco/.rvm/gems/ruby-1.8.7-head/gems/railties-3.0.10/lib/rails/commands.rb:27:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
How to include many ActiveRecord relations after a join?
Trying to load multiple associations in one query:
GroupAssignment.where(groupable_type: 'Product').joins(:product, :packages).includes(:product)
The query works, but I would like to include the packages also. When I modify the query to:
GroupAssignment.where(groupable_type: 'Product').joins(:product, :packages).includes(:product, :packages)
I get the following error:
undefined method `gsub' for :groupable_id:Symbol
The models are defined as follows:
class GroupAssignment
belongs_to :groupable, polymorphic: true
# Defined specific relation to product
# to make join query work
belongs_to :product, foreign_key: 'groupable_id', conditions: "group_assignments.groupable_type = 'Product'"
# Attempted this
has_many :packages, through: :product
end
class Product
has_many :packages
end
class Package
belongs_to :product
end
rake db:migrate returns with error
I ran rake db:migrate and I came across this error in terminal
SQLite3::SQLException: no such table: admin_users: ALTER TABLE "admin_users" ADD "username" varchar(25)/Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/sqlite3-1.3.10/lib/sqlite3/database.rb:91:in `initialize'
/Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/sqlite3-1.3.10/lib/sqlite3/database.rb:91:in `new'
/Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/sqlite3-1.3.10/lib/sqlite3/database.rb:91:in `prepare'
/Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/sqlite3-1.3.10/lib/sqlite3/database.rb:134:in `execute'
/Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/connection_adapters/sqlite3_adapter.rb:329:in `block in execute'
/Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/connection_adapters/abstract_adapter.rb:473:in `block in log'
I looked into my alter_user.rb file class AlterUsers < ActiveRecord::Migration
this is the file 20150825065823_alter_users.rb
def up
rename_table("users", "admin_users.broken")
add_column("admin_users", "username", :string, :limit => 25, :after => "email" )
change_column("admin_users", "email", :string, :limit => 100)
rename_column("admin_users", "broken", "hashed_password")
puts "*** Adding an index is next ***"
add_index("admin_users", "username")
end
def down
remove_index("admin_users", "username")
rename_column("admin_users", "hashed_password", "password")
change_column("admin_users", "email", :string, :default => "" , :null => false)
remove_column("admin_users", "username")
rename_table("admin_users", "users")
end
Request - Response from php server to ruby on rails server. CSRF token issue
We are planning interaction between php script to ruby on rails server and vice-versa.
Whenever I do curl post data from php script, on rails server notifcation displays - "Can't verify CSRF token authenticity". I am passing authenticity_token in post parameters. We need to how to use this token in secure manner on rails server.
<?php
class active_merchant{
private $endpoint_url; // server address or url where data is to be posted.
private $params; // form fields
private $fields_count; // count of fields in credit card
public function __construct(){
$this->endpoint_url = "http://localhost:8080/activemerchant/index";
$token = md5('random');
$this->params = array('name'=>'test','authenticity_token'=>$token);
}
/* function curl_post
makes a curl post to the end point url
global variables
*/
public function curl_post(){
try{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->endpoint_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($this->params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
print_r($response);
//return $response;
}catch(Exception $e){
throw new Exception($e->getMessage(),$e->getCode(),$e->gtLine());
}
}
}
$active_merchant = new active_merchant();
$active_merchant->curl_post();
?>
Rails code -
class ActivemerchantController < ApplicationController
protect_from_forgery except: :index
def index
Rails.logger.debug params.inspect
puts params.inspect
self.response_body = "Hello, world!"
end
end
Can anyone tell us how can we keep our authenticity_token random ,consistent and secure between two servers (php and ruby on rails).
Ruby and Oracle spatial
I have got a geometry 'Geoloc' in Oracle Spatial.I want to manipulate it in Ruby so that it displays the coordinates of all individual rings in the geometry separately
dimanche 30 août 2015
Getting only file name as string
i am trying to upload a file in rails
i have created a model with following code
def self.save(upload,id)
name = upload[:img].original_filename
directory = "public/user_db"
# create the file path
path = File.join(directory, id)
# write the file
File.open(path, "wb") { |f| f.write(upload['img'].read) }
end
end
my view have following field.
<div class="field">
<input type="file" name="img" id="img" placeholder="upload your DP" />
</div>
my controller is calling save function as following :
post = DataFile.save(params,@fbuser.id)
Ruby on rails error rake db:migrate
Whenever I run rake db:migrate RAILS_ENV=development it returns with a syntax error
rake aborted! SyntaxError: /Users/IsaiahxD/.rvm/gems/ruby-2.2.1@rails3tutorial/rails_projects/first_app/db/migrate/20150825050353_create_users.rb:21: syntax error, unexpected keyword_end, expecting end-of-input /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:in require' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:in
block in require' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:240:in load_dependency' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activesupport-4.2.3/lib/active_support/dependencies.rb:274:in
require' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:773:in load_migration' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:769:in
migration' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:764:in disable_ddl_transaction' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:1047:in
use_transaction?' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:1039:in ddl_transaction' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:993:in
execute_migration_in_transaction' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:955:in block in migrate' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:951:in
each' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:951:in migrate' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:819:in
up' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/migration.rb:797:in migrate' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/tasks/database_tasks.rb:137:in
migrate' /Users/IsaiahxD/.rvm/gems/ruby-2.2.1/gems/activerecord-4.2.3/lib/active_record/railties/databases.rake:44:in `block (2 levels) in ' Tasks: TOP => db:migrate (See full trace by running task with --trace)
I checked everything in create_user.rb and cannot seem to find the problem.
class CreateUsers < ActiveRecord::Migration
def up
create_table :users do |t|
t.column "first_name", :string, :limit => 25
t.string "last_name", :limit => 50
t.string "email", :default => "", :null => false
t.string "password", :limit => 40
t.datetime "created_at"
t.datetime "updated_at"
t.timestamps null: false
end
end
def down
drop_table :users
end
end
Nested Form Rails UPDATING
I hope they are good, need to do nested forms with the profile of a user and their respective car.
each user has their own profile:
class PerfilController < ApplicationController
before_filter :authenticate_user!
def index
end
def show
@usuario = current_user
@usuario.perfil ||= Perfil.new
@perfil = @usuario.perfil
end
def update
@usuario = current_user
@perfil = @usuario.perfil
respond_to do |format|
if @usuario.perfil.update_attributes(perfil_params)
format.html {redirect_to @usuario, notice: "Datos Actualizados" }
else
format.html {render action: "show"}
end
end
end
private
def perfil_params
params.require(:perfil).permit(:nombre, :apellido, :rut)
end
end
I want the fund to ensure that each time a user posts a car, you can update your profile. Deputy nested form
<%= simple_form_for(@auto) do |f| %>
<%= f.error_notification %>
<%=f.fields_for @perfil do |perfil_builder|%>
<p>
<%= perfil_builder.label :nombre %><br/>
<%= perfil_builder.text_field :nombre %>
<%= perfil_builder.label :apellido %><br/>
<%= perfil_builder.text_field :apellido %>
<%= perfil_builder.label :rut %><br/>
<%= perfil_builder.text_field :rut %>
</p>
<%end%>
<div class="form-inputs">
<%= f.association :region %>
<%= f.association :ciudad %>
<%= f.association :marca %>
<%= f.input :modelo %>
<%= f.input :version %>
<%= f.input :año %>
<%= f.input :patente %>
<%= f.association :tipo_transmision %>
<%= f.association :combustible %>
<%= f.association :tipo_vehiculo %>
<%= f.association :carroceria %>
</div>
<div class="form-actions">
<%= f.button :submit, :id => 'submit' %>
</div>
<% end %>
The problem is when you want to update does not change the user data but if you publish the article. the error in the console is: Unpermitted parameter: perfil
Best regards friends.
How To Create Clothing Items Model - Different Sizes for Shoes, Shirts, Jeans ect
Im creating an online retail store.
Just wondering how some of you professionals would go about creating a Clothes Model.
Problem Shoes have different sizes like mens 8,9,10,12 ect. Shirts have 38,40,42 chest. Jeans have 32, 34,36. Dresses have size 6, 8 ect.
How would someone go about making an clothing items model. So when someone creates and item, they first click on which category they want. Lets say Shoes, then it brings down a list of shoe sizes and you can then put in the quantity for each shoe size you have and all other attributes like price and ect.
Ruby on Rails: Gmaps4Rails: adding values to @Hash passed from Gmaps4rails.build_markers
I'm new to Ruby on Rails. I'm developing a small Maps Application using gmaps4rails and geocoding gems. My repository is http://ift.tt/1N3lfv6
Right now I'm loading the map with the normal code:
<div style='width: 800px;'>
<div id="map" style='width: 800px; height: 400px;'></div>
</div>
<script type="text/javascript">
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
markers = handler.addMarkers(<%=raw @hash.to_json %>);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
</script>
I want to know a way of adding another Point in the map after the DB is loaded in the map. My goal is to Load the DB in the map (already working), then load another point (where the user is) in the same map. For example.. Why doesn't this work?
<script type="text/javascript">
handler = Gmaps.build('Google');
handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
markers = handler.addMarkers([{<%=raw @hash.to_json %>},{ lat: 43, lng: 3.5}]);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
</script>
thank you
Form not showing up - Ruby on Rails
I'm currently following a Ruby on Rails tutorial book and I've noticed that the newer version of Rails is quite a bit different. A couple of given commands were different than described in the book and I've had to look up a few ways on how to fix these things. Right now though, I don't know what's going wrong. I have created a database table products and I'm simply trying to use a form to display some input components etc to create a new product. The book told me to do this:
<h1>New product</h1>
<% form_for(@product) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.label :description %><br />
<%= f.text_area :description, :rows => 6 %>
</p>
<p>
<%= f.label :image_url %><br />
<%= f.text_field :image_url %>
</p>
<p>
<%= f.label :price %><br />
<%= f.text_field :price %>
</p>
<p>
<%= f.submit "Create" %>
</p>
<% end %>
<%= link_to 'Back', products_path %>
However, the view only shows me the New product header and the link to go back. I've already installed a different gem because the f.error_messages apparently wasn't used anymore either. The problem is, the entire form_for part does not show up anything. Can anybody tell me how I am supposed to change this code to get it to show up on the view for creating a new product?
Thanks!
This is what it shows:
samedi 29 août 2015
Whether to use class variable or database table for user tracking in ruby on rails
Help me in ruby on rails logged in users tracking.
I am confused whether to use class variable or make a database table for tracking currently logged in users in ruby on rails?.
I tried making database table but never use class variable i wonder whether class variable is best to use then i give a try.
Rails order product price ascending and descending by their minimum value has_many relation
I am trying to order my products by their price ascending and descending, but depending on the minimum value.
products `has_many` product_prices through product_offers.
I am using @products.includes(:product_offers).includes(:product_prices).where(...).order("product_prices.price ASC")
or DESC
function of rails, but I need to order the products regarding their minimum prices. I then want to loop like this:
<% for @product in @products %>
<%=@product.product_prices.minimum("price").first%>
<% end %>
Thats why @products
has to have the right order. It is giving me always the same order. What am I doing wrong? The problem is lets say product 1 is in a price range of 10$ - 50$ and product 2 from 20$ - 40$. if I use the order ASC
function it would show product 1 then product 2. If i use the order DESC
function it would show product 1 then product 2, because 50$>40$, but what I want is 20$> 10$ (Minimums) product 2 then product 1.
Thank you very much for help!
Sending messages with Mailboxer gem - Rails
I'm using the Mailboxer gem to send messages. Currently, I can see all sent messages, but the inbox does not have any received messages. I've tried so many things, but maybe a fresh set of eyes can spot the problem. I'm still really new to coding, so please let me know if you need more information that what I've posted below. Thanks!
Messages Controller:
class MessagesController < ApplicationController
before_action :authenticate_user!
def new
@user = User.find_by(id: params[:to].to_i) if params[:to]
@chosen_recipient = User.find_by(id: params[:to].to_i) if params[:to]
end
def create
recipient = User.find(id: params[:to].to_i) if params[:to]
current_user.send_message(recipient, params[:message][:body], params[:message])
flash[:success] = "Message has been sent!"
redirect_to conversations_path
end
private
def set_message
@recipient = User.find(params[:receiver_id])
end
def message_params
params.require(:message).permit(:body)
end
end
Conversations Controller:
class ConversationsController < ApplicationController
before_action :authenticate_user!
before_action :get_mailbox
before_action :get_conversation, except: [:index, :empty_trash]
before_action :get_box, only: [:index]
def index
if @box.eql? "inbox"
@conversations = @mailbox.inbox
elsif @box.eql? "sent"
@conversations = @mailbox.sentbox
else
@conversations = @mailbox.trash
end
@conversations = @conversations.paginate(page: params[:page], per_page: 10)
end
def show
end
private
def get_box
if params[:box].blank? or !["inbox","sent","trash"].include?(params[:box])
params[:box] = 'inbox'
end
@box = params[:box]
end
def get_conversation
@conversation ||= @mailbox.conversations.find(params[:id])
end
def get_mailbox
@mailbox ||= current_user.mailbox
end
end
Conversations Index:
<h1>Your Conversations</h1>
<div class="row">
<div class="col-sm-3">
<ul class="nav nav-pills nav-stacked">
<%= mailbox_section 'inbox', @box %>
<%= mailbox_section 'sent', @box %>
<%= mailbox_section 'trash', @box %>
</ul>
</div>
<div class="col-sm-9">
<% if @box == 'inbox' %>
<%= current_user.mailbox.inbox %>
<% end %>
<% if @box == 'trash' %>
<p><%= link_to 'Empty trash', empty_trash_conversations_path, class: 'btn btn-danger', method: :delete,
data: {confirm: 'Are you sure?'} %></p>
<% end %>
<ul class="list-group">
<%= render partial: 'conversations/conversation', collection: @conversations %>
</ul>
<%= will_paginate %>
</div>
</div>
Conversations Partial:
<li class="list-group-item clearfix">
<div class="btn-group-vertical pull-right">
<% if conversation.is_trashed?(current_user) %>
<%= link_to 'Restore', restore_conversation_path(conversation), class: 'btn btn-xs btn-info', method: :post %>
<% else %>
<%= link_to 'Move to trash', conversation_path(conversation), class: 'btn btn-xs btn-danger', method: :delete,
data: {confirm: 'Are you sure?'} %>
<% end %>
</div>
<p><%= render 'conversations/participants', conversation: conversation %></p>
<p><%= link_to conversation.last_message.body, conversation_path(conversation) %>
<small>(<span class="text-muted"><%= conversation.last_message.created_at.strftime("%-d %B %Y, %H:%M:%S") %> </span>)</small></p>
</li>
New Message View:
<h1>Start a conversation</h1>
<%= form_tag messages_path, method: :post do %>
<div class="form-group">
<%= label_tag 'message[body]', 'Message' %>
<%= text_area_tag 'message[body]', nil, cols: 3, class: 'form-control', required: true %>
</div>
<%= submit_tag 'Send', class: 'btn btn-primary' %>
<% end %>
Route in rails is not working
i have used devise gem for authentication.in same project i have used album model. but my new_user_album_path is giving error.i think there is user id problem.please help me.
this is index.html.erb file
<%= link_to 'New Article', new_user_album_path() %>
<table>
<tr>
<th>Title</th>
<th>Description</th>
</tr>
<% @albums.each do |album| %>
<tr>
<td><%= album.title %></td>
<td><%= album.description %></td>
<td><%= link_to 'Show', user_album_path(album.user,album) %></td>
<td><%= link_to 'Edit', edit_user_album_path(album.user,album) %></td>
<td><%= link_to 'destroy', user_album_path(album.user,album),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
this is albums_controller file
class AlbumsController < ApplicationController
before_action :authenticate_user!
def index
@albums = current_user.albums.all
end
def show
@album = current_user.albums.find(params[:id])
end
def new
@album = current_user.albums.new
end
def edit
@album = current_user.albums.find(params[:id])
end
def create
@album = current_user.albums.build(album_params)
if @album.save
redirect_to action: 'index'
else
render 'new'
end
end
def update
@album = current_user.albums.find(params[:id])
if @album.update(album_params)
redirect_to action: 'show'
else
render 'edit'
end
end
def destroy
@album = current_user.albums.find(params[:id])
@album.destroy
redirect_to action: 'index'
end
private
def album_params
params.require(:album).permit(:title, :description, :user_id)
end
end
it is giving following errror.->
NoMethodError in Albums#index
undefined method `users' for nil:NilClass
Extracted source (around line #2):
<h1>Your Albums</h1>
<%= link_to 'New Article', new_user_album_path(@album.users.id) %>
<table>
<tr>
<th>Title</th>
<th>Description</th>
route.rb file
devise_for :users
# The priority is based upon order of creation: first created priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
resources :users do
resources :albums
end
root 'albums#index'
Quirky Ruby on Rails Syntax
Background: Novice rails developer here learning from Michael Hartl's Ruby on Rails Tutorial (http://ift.tt/1xlbKQQ) in which you develop a basic twitter-like app with a User model and Post model. The users routes are generated from what I understand is the common method of inserting the following into the routes.rb file:
resources :users
Question: I don't understand why when you use:
redirect_to @user
rails sends that request to UsersController#show, but it does so by calling user_url(@user) via:
get "/users/id" => "users#show"
Where does the singular ("user") in user_url come from in the code immediately above? I would think user-url should be users_url or users_path (as I see come up in some places). Just trying to figure out where this singular is coded into rails.
Thanks!
Locales Ruby on Rails issue
I have a issue with Locales. In rails app /config/locales/ I have two files: cs.rb & en.yml. At the end, the output of price is in $. Why is this?
my index.html.erb looks
<% if notice %>
<p id="notice" ><%= notice %></p>
<% end %>
<h1>Zoznam produktov</h1>
<% @products.each do |product| %>
<div class="entry" >
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line" >
<span class="price">
<%= number_to_currency(product.price, :locale => :cs) %>
%>
</span>
</div>
</div>
<% end %>
@Зелёный
First is cs.rb and second is en.yml
# Czech translations for Ruby on Rails
# by Karel Minařík (karmi@karmi.cz)
# contributors:
# - Vít Krchov - http://github.com/vita - Rails 3 update
unless defined?(CzechLocaleI18n::ERROR_MESSAGES)
module CzechLocaleI18n
ERROR_MESSAGES = {
:inclusion => "není v seznamu povolených hodnot",
:exclusion => "je vyhrazeno pro jiný účel",
:invalid => "není platná hodnota",
:confirmation => "nebylo potvrzeno",
:accepted => "musí být potvrzeno",
:empty => "nesmí být prázdný/á/é",
:blank => "je povinná položka", # alternate formulation: "is required"
:too_long => "je příliš dlouhý/á/é (max. %{count} znaků)",
:too_short => "je příliš krátký/á/é (min. %{count} znaků)",
:wrong_length => "nemá správnou délku (očekáváno %{count} znaků)",
:not_a_number => "není číslo",
:greater_than => "musí být větší než %{count}",
:greater_than_or_equal_to => "musí být větší nebo rovno %{count}",
:equal_to => "musí být rovno %{count}",
:less_than => "musí být méně než %{count}",
:less_than_or_equal_to => "musí být méně nebo rovno %{count}",
:odd => "musí být liché číslo",
:even => "musí být sudé číslo",
:not_an_integer => "musí být celé číslo"
}
end
end
{ :'cs' => {
# ActiveSupport
:support => {
:array => {
:two_words_connector => ' a ',
:last_word_connector => ' a ',
:words_connector => ', '
},
:select => {
:prompt => 'Prosím vyberte si',
}
},
# Date
:date => {
:formats => {
:default => "%d. %m. %Y",
:short => "%d %b",
:long => "%d. %B %Y",
},
:day_names => %w{Neděle Pondělí Úterý Středa Čtvrtek Pátek Sobota},
:abbr_day_names => %w{Ne Po Út St Čt Pá So},
:month_names => %w{~ Leden Únor Březen Duben Květen Červen Červenec Srpen Září Říjen Listopad Prosinec},
:abbr_month_names => %w{~ Led Úno Bře Dub Kvě Čvn Čvc Srp Zář Říj Lis Pro},
:order => [:day, :month, :year]
},
# Time
:time => {
:formats => {
:default => "%a %d. %B %Y %H:%M %z",
:short => "%d. %m. %H:%M",
:long => "%A %d. %B %Y %H:%M",
},
:am => 'am',
:pm => 'pm'
},
# Numbers
:number => {
:format => {
:precision => 3,
:separator => '.',
:delimiter => ',',
:significant => false,
:strip_insignificant_zeros => false
},
:currency => {
:format => {
:unit => 'Kč',
:precision => 2,
:format => '%n %u',
:separator => ",",
:delimiter => " ",
:significant => false,
:strip_insignificant_zeros => false
}
},
:human => {
:format => {
:precision => 1,
:delimiter => '',
:significant => false,
:strip_insignificant_zeros => false
},
:storage_units => {
:format => "%n %u",
:units => {
:byte => "B",
:kb => "KB",
:mb => "MB",
:gb => "GB",
:tb => "TB",
}
},
:decimal_units => {
:format => "%n %u",
:units => {
:unit => "",
:thousand => "Tisíc",
:million => "Milion",
:billion => "Miliarda",
:trillion => "Bilion",
:quadrillion => "Kvadrilion"
}
}
},
:percentage => {
:format => {
:delimiter => ''
}
},
:precision => {
:format => {
:delimiter => ''
}
}
},
# Distance of time ... helper
# NOTE: In Czech language, these values are different for the past and for the future. Preference has been given to past here.
:datetime => {
:prompts => {
:second => "Sekunda",
:minute => "Minuta",
:hour => "Hodina",
:day => "Den",
:month => "Měsíc",
:year => "Rok"
},
:distance_in_words => {
:half_a_minute => 'půl minutou',
:less_than_x_seconds => {
:one => 'necelou sekundou',
:other => 'ani ne %{count} sekundami'
},
:x_seconds => {
:one => 'sekundou',
:other => '%{count} sekundami'
},
:less_than_x_minutes => {
:one => 'necelou minutou',
:other => 'ani ne %{count} minutami'
},
:x_minutes => {
:one => 'minutou',
:other => '%{count} minutami'
},
:about_x_hours => {
:one => 'asi hodinou',
:other => 'asi %{count} hodinami'
},
:x_days => {
:one => '24 hodinami',
:other => '%{count} dny'
},
:about_x_months => {
:one => 'asi měsícem',
:other => 'asi %{count} měsíci'
},
:x_months => {
:one => 'měsícem',
:other => '%{count} měsíci'
},
:about_x_years => {
:one => 'asi rokem',
:other => 'asi %{count} roky'
},
:over_x_years => {
:one => 'více než rokem',
:other => 'více než %{count} roky'
},
:almost_x_years => {
:one => 'téměř rokem',
:other => 'téměř %{count} roky'
}
}
},
:helpers => {
:select => {
:prompt => "Prosím vyberte si"
},
:submit => {
:create => "Vytvořit %{model}",
:update => "Aktualizovat %{model}",
:submit => "Uložit %{model}"
}
},
:errors => {
:format => "%{attribute} %{message}",
:messages => CzechLocaleI18n::ERROR_MESSAGES
},
# ActiveRecord validation messages
:activerecord => {
:errors => {
:messages => {
:taken => "již databáze obsahuje",
:record_invalid => "Validace je neúspešná: %{errors}"
}.merge(CzechLocaleI18n::ERROR_MESSAGES),
:template => {
:header => {
:one => "Při ukládání objektu %{model} došlo k chybám a nebylo jej možné uložit",
:other => "Při ukládání objektu %{model} došlo ke %{count} chybám a nebylo možné jej uložit"
},
:body => "Následující pole obsahují chybně vyplněné údaje:"
},
:full_messages => {
:format => "%{attribute} %{message}"
}
}
}
}
}
#
# Sample localization file for English. Add more files in this directory for other locales.
# See http://ift.tt/1LBF4Xo for starting points.
en:
hello: "Hello world"
How to Integrate HDFC Payment Gateway in Rails 3
How to Integrate HDFC Payment Gateway in Ruby on Rails 3 application.
vendredi 28 août 2015
How to seed sqlite3 with Rails seed.rb?
To whom it may concern,
Basic Rails app. Created a model called "Images" via rails g model images url:string
Put some jpg's in the Public folder and set up seed.rb file like this:
images = Image.create([
{ url: "/public/images/01.jpg"},
{ url: "/public/images/02.jpg"},
{ url: "/public/images/03.jpg"},
{ url: "/public/images/04.jpg"},
{ url: "/public/images/05.jpg"},
{ url: "/public/images/06.jpg"},
{ url: "/public/images/07.jpg"},
{ url: "/public/images/08.jpg"},
{ url: "/public/images/09.jpg"},
{ url: "/public/images/10.jpg"},
{ url: "/public/images/11.jpg"},
{ url: "/public/images/12.jpg"},
{ url: "/public/images/13.jpg"},
{ url: "/public/images/14.jpg"},
{ url: "/public/images/15.jpg"},
{ url: "/public/images/16.jpg"},
{ url: "/public/images/17.jpg"},
{ url: "/public/images/18.jpg"},
{ url: "/public/images/19.jpg"},
{ url: "/public/images/20.jpg"}
])
Ran rake db:setup
, rake db:seed
, and rake db:migrate
to try to seed the sqlite3 data base.
I go into db/development.sqlite3
and run .databases
and find nothing. I run .tables
and find nothing.
sqlite> .databases
seq name file
--- --------------- ----------------------------------------------------------
0 main
Why did this not seed the database?
Thanks!
Peter
How to render application.html.erb in a Rails app?
My questions is really simple:
How can I render the application.html.erb
view in a rails app?
I've tried adding a method to the application.controller.js
files:
def amethod
end
And then updating the routes.rb
file:
get '/', to: 'application#amethod'
to no avail. I get this error message:
Missing template application/amethod with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in: * "/Users/peterward/Directory/mini-project/app/views"
It's looking for the html.erb
view in the app/layouts/views
directory instead of the app/layouts
directory. How can I change this?
Thanks!
Peter
How can I override a default scope in a has_many :through association?
Override to a default scope isn't being persisted (in a useful way) in a has_many :through association.
Here's the relevant stuff from the models:
class User
has_one :invitation
default_scope where(registered: true)
end
class Invitation
belongs_to :user, conditions: { registered: [true, false] }
belongs_to :program
end
class Program
has_many :invitations
has_many :users, through: :invitations
end
Finding users through invitations works as expected.
Invitation.joins(:user)
generates this:
SELECT `invitations`.* FROM `invitations` INNER JOIN `users` ON `users`.`id` = `invitations`.`user_id` AND `users`.`registered` IN (1, 0)
Given this, I'd assume that Program.last.users should find all relevant users, whether registered is true or false. Instead, I get this:
SELECT `users`.* FROM `users` INNER JOIN `invitations` ON `users`.`id` = `invitations`.`user_id` WHERE `users`.`registered` = 1 AND `invitations`.`program_id` = 52 AND (`users`.`registered` IN (1, 0))
This is the SQL I expect. How do I create an association that gives me this?
SELECT `users`.* FROM `users` INNER JOIN `invitations` ON `users`.`id` = `invitations`.`user_id` WHERE `users`.`registered` IN (1, 0) AND `invitations`.`program_id` = 52
More context: I'm using rails 3.1.3, and upgrading rails isn't a viable option before this feature needs to go out. Getting rid of default_scope isn't a thing I can do either.
Why isn't rspec failing on what should be a NameError inside a Model?
I have an rspec that looks like:
it "should test nil" do
u = Upload.new
u.save!
u.my_method!
end
The method looks like:
class Upload < ActiveRecord::Base
def my_method!
puts "Made it to my method :)"
not_defined_var
puts "But didn't get this far :("
end
end
Clearly, not_defined_var should give a "NameError: undefined local variable or method".
My output prints
Made it to my method :)
.
Finished in 1.54 seconds
1 example, 0 failures
I feel like I'm missing something essential. Got any ideas?
multiple database connection mySQL in rails 3.2
I have the following scenario: I have two databases in different hostings. I have to put the same data in each databases , when I insert ,with my rails application, new data. My question is: Is possible in rails? I mean , i want to store the same data (maybe using just one model) in two different mySQL databases. Can you give me advice?
thank you.
Has_many through and belongs to in Rails
I am working on a Rails app where a User can create a magazine and another user can subscribe to that magazine. I want to know the best way to do this.
Currently I have a subscription model that builds from current user when created and users the current magazine as the magazine_id. This allow me to have a table of user_ids and magazine_ids. This allows me to see all the subscriptions but it means I cant easily check all the magazines someone subscribes to or check all the subscribers of a magazine.
When I try to use has_many :through, it throws up an error with building from current user. I have put in the relevant code below, hopefully it covers it all and thanks in advance.
User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :magazines
has_many :subscriptions
end
Subscription model:
class Subscription < ActiveRecord::Base
belongs_to :user
belongs_to :magazine
end
Magazine model:
class Magazine < ActiveRecord::Base
belongs_to :user
has_many :subscrptions
has_many :users
end
The snippet of code from the subscription controller that throws up the error when I use has many through
def new
@subscription = current_user.subscriptions.build
@sub = Sub.find(params[:sub_id])
end
Hopefully that is enough for someone to figure out, if not please ask me for the other code or information.
SQL query to select a User's friends via an associated model
My question is: for a given User, what SQL command could be used to select all associated initiators/initiatees for which the associated Relation is confirmed and of a given type?
The Ruby is as follows:
class User < AcitveRecord::Base
has_many :relations
end
class Relation < ActiveRecord::Base
belongs_to :initiator, class_name: "User"
belongs_to :initiatee, class_name: "User"
end
class CreateRelations < ActiveRecord::Migration
def change
create_table :relations do |t|
t.references :initiator
t.references :initiatee
t.boolean :is_confirmed, default: false
t.integer :type
end
end
end
Multiple simultaneous remote file uploads ruby on rails
How can be multiple files upload simultaneous and check upload process ( I mean time left )
On rails application I have multiple text fields, they are for remote file urls like http://ift.tt/1WWBaOU etc and these all files should be downloaded to a temp_uploads folder.
for this I have written code in remotefiles controller like below.
def remotefiles
params[:reference_file_url].each do |rfile|
temp_file = File.new("/public/temp_uploads", "w")
open(temp_file, 'wb') do |file|
file << open(rfile).read()
end
end
end
where rfile is remote file url.
I also have defined route remotefiles to call it in ajax
my ajax call sends form data in serialize format and this controller uploads all files 1 by 1.
with this code i have to wait untill all files are uploaded to folder that is obviously not acceptable.( I mean client asked me to reduce wait time by uploading all files simultaneous )
is there any way to get it done, all my code is custom and is not using any gem
jeudi 27 août 2015
Error handling with Grape, Rails and ActiveRecord
I have created a my first API service using the Grape GEM and Rails. The API's work perfectly, but I'm struggling with Error handling and the search for valuable tutorials have been without result.
In the tutorial that I followed, the only Error handling coverage they followed was this:
rescue_from ActiveRecord::RecordNotFound do |e|
error!(message: e.message, status: 404)
end
rescue_from ActiveRecord::RecordInvalid do |e|
error!(message: e.message, status: 422)
end
Two Issues have led me to the conclusion that this is not sufficient:
- I am thrown an error that indicates the following: "compared with non class/module" for ActiveRecord::RecordInvalid
- When I submit an API request that passes the API rules, but fails the Model validation, The request just hangs..i.e. nothing happens. I can see the response on my localhost server log (i.e. email already exists) but in Postman & and swagger it just continues loading with no response.
Can anyone point me to a tutorial that's fully focussed on Grape exception handling? I am so confused with regards to handling Model Validations through API calls etc. and could do with some guidance.
Rails 3 head first rails Mebay application error
I am using rails 3 and learning it fron head first rails book. I am in chapter 2 creating Mebay application with ads table.
The steps that I did are
1.rails new MeBay
2.cd to MeBay directory
3.rails g model ad name:string description:text price:decimal seller_id:integer email:string imr_url:string
4.rake db:migrate
5.rails generate controller ads
6.show.html.erb created in folder app/views/ads as below.
<html>
<head>
<title> </title>
</head>
<body>
<p>
<b>Name:</b>
</p>
<p>
<b>Description:</b>
</p>
<p>
<b>Price:</b>
</p>
<p>
<b>Seller Id:</b>
</p>
<p>
<b>Email:</b>
</p>
</body>
</html>
- config/routes.rb file
MeBay::Application.routes.draw do controller 'ads' do match 'ads/:id' => :show end end
When I started rails server and in browser
I only see labels with empty values. in other words, I don't see values next to the labels as the book says on page 63.
so far going good.
page 65 says we need to tell the model to read the record from the ads table in the database. But I have created only the ads table I don't have values entered in database for this application like page 65 shows an example.
When I don't have data, I added the code like page 69 says in views/ads/show.html.erb as
<html>
<head>
<title> </title>
</head>
<body>
<p>
<b>Name:</b><%= @ad.name %>
</p>
<p>
<b>Description:</b><%= @ad.description %>
</p>
<p>
<b>Price:</b><%= @ad.price %>
</p>
<p>
<b>Seller Id:</b><%= @ad.seller_id %>
</p>
<p>
<b>Email:</b><%= @ad.email %>
</p>
<p>
<img src="<%= @ad.img_url %>"/>
</p>
</body>
</html>
My test drive on this code displayed error
NoMethodError in Ads#show
Showing C:/Ruby193/RailsProject/MeBay/app/views/ads/show.html.erb where line #7 raised:
undefined method `name' for nil:NilClass Extracted source (around line #7):
4: </head>
5: <body>
6: <p>
7: <b>Name:</b>><%= @ad.name %>
8: </p>
9: <p>
10: <b>Description:</b><%= @ad.description %>
Please help on this. I have searched all the forums and worked on hours on this problem. Thank you for the help.
How can I conditionally call attributes within ActiveRecord's where?
I have a piece of code that looks something like:
foreign_object = (some_test) ? nil : <some foreign_object>
Document.where(foreign_id: foreign_object, status: "Working", ... )
If foreign_object is nil, It will only find Documents with foreign_id = NULL. Is there a way to conditionally put the foreign_id in? I essentially want to write:
Document.where(foreign_id: foreign_object if foreign_object, status: "Working", ...)
Referencing Associated Object Returns Nil
I have two models.
class User < ActiveRecord::Base
has_one :message
end
class Message < ActiveRecord::Base
belongs_to :user
end
If I have a created user with an associated Message
and I delete that message and create a new one like, user.message
returns nil. For example.
user = User.create
message = Message.create(user_id: user.id)
Message.where(user_id: user.id).destroy_all
Message.create(user_id: user.id)
# Now if I call this below, it always returns nil
user.message
Why does this occur? Shouldn't Rails 3 pick up on that change? How do I fix this?
Sortable custom column in ActiveAdmin index view : joins, group and count hell
We're using ActiveAdmin for our admin view, here's the current index code. The Book model retrieves data from a single "books" postgres table :
class Book < ActiveRecord::Base
has_many :stories, class_name: "BookStory"
...
ActiveAdmin.register Book do
index do
column :id
column :title
column :subtitle
column :isbn_13
default_actions
end
...
I would like to add a "stories" column in our index view. A "story" is an action from a user, associated with a book. The stories are stored in a "book_stories" table.
class BookStory < ActiveRecord::Base
belongs_to :user,
belongs_to :book,
From a SQL point of view, this is how I would like to implement the query into ActiveAdmin. This query gives me the wanted result into pgAdmin3 :
SELECT books.id,books.title,books.subtitle,books.isbn_13,COUNT(book_stories.book_id) AS count
FROM books
INNER JOIN book_stories ON books.id = book_stories.book_id
GROUP BY books.id
ORDER BY count DESC
LIMIT 30;
And I really don't know how to implement a sortable "Stories" column into our admin view. By sortable, I mean, being able to sort the book like by their stories count. I managed to show the stories count per book with this code, but the column isn't sortable :
ActiveAdmin.register Book do
index do
column :id
column :title
column :subtitle
column :isbn_13
column :stories do |book|
BookStory.joins(:book).group.where("books.id = #{book.id}").count
default_actions
end
...
Any ideas ?
form_for won't pass id Rails 3.2
I have the following strange situation:
I call my edit action through a link_to
,
<%= link_to 'Edit', companies_edit_path(:id => company.id)%>
And everything is fine. I mean, i reach the edit page with the correct dates loaded. This is my edit page:
<%= form_for @company ,:url => {:action => :update, :controller => :companies, :method => :put} do |f| %>
<% if @company.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@company.errors.count, "error") %> prohibited this order from being saved:</h2>
<ul>
<% @company.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-sm-2" for="name">name:</label>
<div class="col-sm-10">
<%= f.text_field :name, size: 40 %>
</div>
</div>
...
...
</form>
<% end %>
i took off all the things into the form_for, I don't think they are important. Now , when i click on submit i should go in my update action (as you can see in the form_for declaration). But it said to me that isn't able to find the company cause it doesn't have id passed. this is my controller:
def edit
@company = Company.find(params[:id])
end
def update
@company = Company.find(params[:id])
respond_to do |format|
if @company.update_attributes(params[:company])
format.html { redirect_to companies_index_path, :notice => 'Aggiornato.' }
format.json { head :no_content }
else
format.html { render :action => "edit" }
format.json { render :json => @company.errors, :status => :unprocessable_entity }
end
end
end
these are my routes:
get "companies/index"
get "companies/new"
get "companies/search"
get "companies/edit"
post "companies/create"
put "companies/update"
devise_for :users
resource :calendar, :only => [:show]
resources :events
root :to => 'home#index'
Do you see anything strange?
Tag Cloud - Show only whats visible
I have a list of categories. When you click on a category lets say Computers it should only show a tag cloud of the items in that category in this case Computers. Tags from the Mobile Phone category should not be showing.
Currently my tag cloud shows all tags across all categories.
Im using the Acts_as_tagable_gem http://ift.tt/Pchlg6
How would someone go about showing only the tags inside that category?
Here is my view. Please refer to tag_cloud
<p id="notice"><%= notice %></p>
<div class = "col-md-3">
<h1>
<strong><%= @category.name %></strong>
</h1>
</div>
<div class = "col-md-9">
<div id="tag_cloud">
<% tag_cloud(@tags, %w[s m l]) do |tag, css_class| %>
<%= link_to tag.name, tag_path(tag.name, id: @category.id), class: css_class %>
<% end %>
</div>
</div>
<div class = "col-md-12">
<div class="line-separator"></div>
</div>
<div class = "col-md-12">
<div id="items" class="transitions-enabled">
<% @items.each do |item| %>
<div class="box panel panel-default">
<div class="itemlisttitle"><%= item.title %></div>
<%= link_to image_tag(item.image.url (:medium)), item %>
<div class ="panel-body">
<div class = "itemlistprice">$<%= item.price %></div>
<div class = "itemlistretailer"><%= image_tag item.user.avatar(:thumb) %> Retailer: <%= link_to item.user.username, item.user %></div>
</div>
</div>
<% end %>
</div>
</div>
Routes Please refer to the last line
Rails.application.routes.draw do
resources :categories
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
resources :users
get 'user_items' => 'users#show_user_items'
root 'items#home'
get 'signup' => 'users#new'
get 'show' => 'users#show'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :items
get 'items_new' => 'items#new'
get 'tags/:tag', to: 'categories#show', as: :tag
Category Controller Show Action.
def show
@tags = Item.tag_counts_on(:tags)
if params[:tag]
@items = Item.tagged_with(params[:tag])
else
@items = Item.where(category_id: @category.id).order("created_at DESC")
end
end
No such file or directory - questions.csv
Hi friends i am getting above error when i tried to import .csv file from the user. I tried with different methods but it is not working. Please help me resolve this issue. I am new to Ruby family. Below i am mentioning all the codes i have tried .
1 question.rb
def import(file)
CSV.foreach(file.name, :headers => true) do |row|
values = row.inject([]){|k,v| k<<"'#{v}'";k}.join(',')
sql = "INSERT INTO questions (description,question_type_id,mark) VALUES #{values}"
@question = Question.find_by_sql(sql)
end
end
error is :-NoMethodError (undefined method `name' for "questions.csv":String
2 question.rb
def import(file)
f = File.open(file)
CSV.foreach(f, :headers => true) do |row|
values = row.inject([]){|k,v| k<<"'#{v}'";k}.join(',')
sql = "INSERT INTO questions (description,question_type_id,mark) VALUES #{values}"
@question = Question.find_by_sql(sql)
end
end
error is :- Errno::ENOENT (No such file or directory - questions.csv
3 question.rb
def import(file)
path = File.expand_path(file)
CSV.foreach(path, :headers=> true) do |row|
question_hash = row.to_hash
@question = Question.where(:id=> question_hash["id"])
if @question.count == 1
@question.first.update_attributes(question_hash)
else
Question.save!(question_hash)
end # end if !@question.nil?
end # end CSV.foreach
end # end self.import(file)
error is :- Errno::ENOENT (No such file or directory - /var/www/VirtualX/questions.csv): app/models/question.rb:94:in import' app/controllers/questions_controller.rb:824:in
import'
4 question.rb
def import(file)
CSV.foreach(file, :headers => true) do |row|
values = row.inject([]){|k,v| k<<"'#{v}'";k}.join(',')
sql = "INSERT INTO questions (description,question_type_id,mark) VALUES #{values}"
@question = Question.find_by_sql(sql)
end
end
error is :- Errno::ENOENT (No such file or directory - questions.csv):
5 question.rb
def import(file)
CSV::Reader.parse(file) do |row|
values = row.inject([]){|k,v| k<<"'#{v}'";k}.join(',')
sql = "INSERT INTO questions (description,question_type_id,mark) VALUES #{values}"
@question = Question.find_by_sql(sql)
end
end
In this case code is working but not taking value of csv which i have uploaded instead taking name of that csv file . I am getting below error .
****1mINSERT INTO questions (description,question_type_id,mark) VALUES 'questions.csv'[0m Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''questions.csv'' at line 1: INSERT INTO questions (description,question_type_id,mark) VALUES 'questions.csv' Completed in 407ms**
**ActiveRecord::StatementInvalid (Mysql::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''questions.csv'' at line 1: INSERT INTO questions (description,question_type_id,mark) VALUES 'questions.csv'): app/models/question.rb:95:in import' app/models/question.rb:91:in
import' app/controllers/questions_controller.rb:824:in `import'****
Please help me friends i need to insert data of .csv file to corresponding table. I am using Ruby 1.8.7 and Rails of 3
And also suggest any other good method to import. And also tell me What is parse and foreach and what their functionalities .
mercredi 26 août 2015
Where condition inside HTML.erb file using Ruby On Rails
I have an .html.erb file which is to print the customer details on a form. In my database table "customers" there are "User_id" filed and "creater_id" field is there. I want to print the customer_name of the customer where user_id eqaul to creater_id. How to implement it into my html file ?
Migrating a Rails 2 app to Rails 3: `image_path` throws "undefined local variable or method 'config'"
background
I am trying to migrate an old Rails 2 (Ruby 1.8.7) app to Rails 3.0.9 (Ruby 1.9.3) — yes it's a stepping stone to get it to Rails 4 and Ruby 2.2 — and I've hit the following problem.
The original app makes extensive use of an old Active Form
gem which we've hacked slightly to support Ruby 1.9.
It mostly works, but there appears to be some issue with how it interacts with the ActionView::Helpers::AssetTagHelper
that's part of ActionPack 3.0.9
.
In my specific case I have an ActiveForm::DateCalendarSection
(built dynamically) which subclasses ActiveForm::Element::Section
, which, according to self.class.ancestors
, is a subclass of ActionView::Helpers::AssetTagHelper
. Looking at the ActiveForm
source however there is no mention of AssetTagHelper
or asset_tag_helper
so how they are actually connected remains a mystery to me.
Problem
Calls to the method image_path
result in an error
undefined local variable or method 'config'
The call to image_path
is simply a wrapper around a call to compute_public_path
in ActionView::Helpers::AssetTagHelper
# File actionpack/lib/action_view/helpers/asset_tag_helper.rb, line 741
def compute_public_path(source, dir, ext = nil, include_host = true)
return source if is_uri?(source)
source += ".#{ext}" if rewrite_extension?(source, dir, ext)
source = "/#{dir}/#{source}" unless source[0] == //
source = rewrite_asset_path(source, config.asset_path)
has_request = controller.respond_to?(:request)
if has_request && include_host && source !~ %{^#{controller.config.relative_url_root}/}
source = "#{controller.config.relative_url_root}#{source}"
end
source = rewrite_host_and_protocol(source, has_request) if include_host
source
end
Diving into that with binding.pry
it's evident that config
is indeed not defined. Likewise controller
is also not defined.
Question
What would have changed between Rails 2 and Rails 3, such that methods from ActionView::Helpers::AssetTagHelper
can no longer access Rails' config
or the current controller
?
Writing test in Capybarra for link_to
Hello i have some code in my view template thats a HAML file.
Please refer to last line.
%section.black_background.white_foreground
.container
.pricing-blurb
%h2{ style: 'margin: 30px 0 40px;' } Increase your productivity with Trigger.
%p
Pricing is simple:
%strong $8
per employee, per month. -
%strong That's it.
%p This means unlimited Companies, Projects and Clients, + ongoing customer support.
= link_to 'Get Started', new_signup_path, class: 'signup-button'
How do i make a Capybarra test for this?
I did some playing around but cant get it to work. I wrote something along the lines of this.
it 'has the correct links in the page' do
within '.pricing-blurb' do
expect(find_link('Get Started')[:href]).to eql(new_signup_path)
end
end
But i know its wrong because my code isn't a :href
Thank you.
Ruby-Rails Running code and saving the output in the database
My code reads in log files and parses the data. The output gets me something that looks like this:
name: jon
domain: jon@gmail.com
date: 2-12-2012
I have created my database called "databases" And I want to have my parsed data updated in the database without using simply CRUD actions. (I don't want to manually create each log) My question is how would I go about automatically taking the parsed data (after running my code) and having it save and show up in the database.
Thanks
Devise mass assignment error for failed logins when using username as login
HAving a weird one.
I've set up devise to authenticate using either a username or an email as per Devise login with username
I can log in absolutely fine with a correct username or email with a password. If I put something incorrect in, I get a
Can't mass-assign protected attributes: login
Can't work out quite what's going on. I assume it's something to do with Devise killing the session, but not sure why it would be doing anything with the login field at that point....
rails 3.2 searching action. how to pass results to another action
I should create a search page in which i have to save in an Array all the results of the searching. I had two problems:
1) I used the following statement:
Company.joins(:references).where(sql_string)
that returns an ActiveRecord:Relation
and it's not good for me cause i have to display these results in the index action , in which i use an each
statement. So , to overcame this problem i used the to_a
. I checked the .class
of my variable and with the to_a
it passed from ActiveRecord:Relation
to Array
. So , it seems that this solve the problem.
Company.joins(:references).where(sql_string).to_a
2) Now, i have to pass this variable (Array
) into my index
action. I executed the search in the action called search
:
def search
...
@companies = Company.joins(:references).where(sql_string).to_a
end
Now, i want to pass this to index
:
def index
@companies ||= Company.all
end
I used @companies ||= Company.all
cause i think that the @companies
is and istance variable and it should be available in all the actions of the class. Isn't it? By the way, it doesn't workl. I mean , the results are not shared through the two methods. Also , in the search
action i don't know how to call index
action. I used the redirect_to
but this bring me to another problem.
def search
...
@companies = Company.joins(:references).where(sql_string).to_a
redirect_to companies_index_path
end
The second time i call the search action it brings me into the index action.As i insered the searching value. At really he still had the past searching in memory, and i don't want this behavior. So , in other words, i want to:
-
passing @companies searching result to index action.
-
avoid the loop between
search-index
. So in every new request resets the old searching. -
i want to know if it's correct the casting with the
to_a
to bring anActiveRecord:Relation
toArray
.
Thank You.
Locales Ruby on Rails issue
I have a issue with Locales.
In rails app /config/locales/ I have two files: cs.rb & en.yml
my index.html.erb looks
<% if notice %>
<p id="notice" ><%= notice %></p>
<% end %>
<h1>Zoznam produktov</h1>
<% @products.each do |product| %>
<div class="entry" >
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line" >
<span class="price">
<%= number_to_currency(product.price, :locale => :cs) %>
%>
</span>
</div>
</div>
<% end %>
At the end, the output of price is in $, I really don't understand why.
Thanks.
Do i have to install rails framework to deploy website written in rails on server?
Do I have to install rails framework
to deploy a website written in rails on server ?
Really, I am at online website written in rails and i don't know how this website was deployed. and when i write rails -v
it tells me rails isn't installed
also i tried to run rvm -v
and rbenv -v
i get the same response not installed
Ruby on Rails and Microsoft SQL server
I am asked to build a website with ruby on rails using a SQL server backend. I have only built sites with sqlite and postgres so I am a bit unsure. I did some digging and found a gem I can use.
activerecord-sqlserver-adapter http://ift.tt/VHGT00
1) I am wondering if I use this plugin, does it mean I can still set up models and using active record searches such as where()
2) If users are pre created in the SQL through a EPRS system, will I still be able to integrate devise with that?
3) They are going to give me a bak file for the SQL server and asked me to set up my own sql server on my mac during the development phase, is this possible or do I have to pay for a microsoft sql server license to do this?
Thank you very much in advance, any help would be deeply appreciated. Thanks again.
Uploading files - undefined method 'attr_accessible'
I checked out a Rails sample project, for jquery fileuploads The project itself works, but it's running on 3.2.13.
Now I want to use this code in my own Project, which is based on Rails 4.2.3.
First it didn't work, cause I ran into the error undefined method 'attr_accessible' for #<Class:0x007f7428f82f98>
I found out, that there was a change in Rails 4.1, regarding the "mass alignment". Now I am trying to convert this to Rails 4...
Here is my Upload model:
class Upload < ActiveRecord::Base
attr_accessible :upload
has_attached_file :upload
include Rails.application.routes.url_helpers
def to_jq_upload
{
"name" => read_attribute(:upload_file_name),
"size" => read_attribute(:upload_file_size),
"url" => upload.url(:original),
"delete_url" => upload_path(self),
"delete_type" => "DELETE"
}
end
end
I have deleted everything inside the model-class, and got rid of the error. But now my Rails Application does not accept the uploads. (Nothing happens, when I try to upload a file) I have added the following code to my controller, but it still doesn't accept my uploaded files.
uploads_controller:
def upload_params
params.require(:upload).permit(:name, :size, :url, :delete_url, :delete_type)
end
Can you guys help me, to get this to work on Rails 4?
Best regards
mardi 25 août 2015
How to link my courses/show.html.erb to the current_course?
I'm creating an app that allows users to access different courses on video (each course has its own 4 or 5 videos, and each video has its own page).
I created a courses_controller
which allows me to index and show the courses stored in the database.
Courses_controller.rb :
class CoursesController < ApplicationController
before_action :set_course, only: [:show]
skip_before_filter :verify_authenticity_token
before_filter :authorize , except: [:index, :show]
def index
@courses = Course.all
end
def show
end
private
# Use callbacks to share common setup or constraints between actions.
def set_course
@course = Course.find(params[:id])
end
def authorize
unless User.find_by_id(session[:user_id]) and User.find_by_id(session[:user_id]).active == true
redirect_to subscriptions_path, :notice => "Vous devez souscrire à un abonnement pour avoir accès a cette page"
end
end
Each course is stored in a seeds.rb file.
courses/index.html.erb
lists the courses, courses/show.html.erb
shows the presentation of a specific course.
How to create a link to the current course from the show.html.erb page? I thought about add a link for each course in the seeds, but it don't look possible.
Any idea?
Is it normal to cache a script tag?
I have a partial like this:
<script type="text/javascript">
-- javascript code here --
</script>
I was trying to use "Fragment Caching":
<% cache "script_code" do %>
<script type="text/javascript">
-- javascript code here --
</script>
<% end %>
Is it common to use "Fragment Caching" like this?
Multiple devise_for routes for the same rails resource
I am working on an existing web application that uses Rails 3 and Devise. My task at the moment is to add a JSON API to the application. I have created a Mobile::SessionsController (< Devise::SessionsController) that implements '#create' with a data-only response.
The issue is in the routing. Right now, the relevant parts of routes.rb are as follows:
# For the web app:
devise_for :users, :controllers => {:sessions => 'sessions',
:registrations => 'registrations'}
as :user do
get "/login" => "devise/sessions#new"
get "/logout" => "devise/sessions#destroy", :as => :logout
post '/signup' => 'registrations#signup', :as => :signup
end
# And for the API, later on:
namespace :api do
namespace :user do
devise_for :users, :controllers => {:sessions => 'mobile/sessions'},
skip: :all
devise_scope :user do
post 'login' => 'mobile/sessions#create'
end
...
The data endpoint is at /api/user/login. rake routes lists the following:
api_user_login POST /api/user/login(.:format) api/user/mobile/sessions#create
In my spec, there's the following:
describe Mobile::SessionsController do
render_views
describe '#create' do
context 'for some condition' do
let(:params) do
{
# basic params
}
end
before do
post :create, params.merge(format: :json)
end
it 'should render a json response' do
expect(response.headers['Content-Type']).to eq 'application/json; charset=utf-8'
end
...
When I run the spec, it gives the following error:
AbstractController::ActionNotFound: Could not find devise mapping for path "/mobile/sessions/create.json?params=blah.
This may happen for two reasons:
1) You forgot to wrap your route inside the scope block. For example:
devise_scope :user do
get "/some/route" => "some_devise_controller"
end
2) You are testing a Devise controller bypassing the router.
If so, you can explicitly tell Devise which mapping to use:
@request.env["devise.mapping"] = Devise.mappings[:user]
I've tried many different configurations within the second devise_for block (modules, whether or not to use skip: :all, removing the second devise_for entirely, putting it at different levels of the namespace) and I can't shake this error. My guess is that the second option there (the devise.mapping bit) is not the solution as it seems like it's not supposed to be bypassing the router at all. And since I have the route in precisely the sort of block it suggests for the first option, I'm befuddled as to how to fix this thing. How can I get this thing working?
Appreciate the help!
Filter by windows function in rails has_many relationship
Using Rails 3.2.21, postgresql db
I need to get the first 3 comments for a set of posts, and I want to get them all in a single query.
class Post < ActiveRecord::Base
has_many :comments
has_many :comments_latest3, :class_name => 'Comment',
:order => 'created_at DESC', :conditions => 'latest_rank <= 3',
:select => 'comments.*,
ROW_NUMBER() OVER(PARTITION BY discussion_id ORDER BY created_at DESC)
AS latest_rank'
...
This generates
select *, latest_rank from comments where discussion_id in ... and latest_rank<=3
Which is invalid because latest_rank doesn't exist yet. Also I can't use the window function directly in the where clause. So what I need is
select *
from (select *, latest_rank from comments where discussion_id in ...)
where latest_rank<=3
Not sure how to get this done, finder_sql doesn't seem to be working for me.
What is the best way to cache a home page?
I have a simple home page, like that:
index view with partials:
-
header
-
how_it_works
-
benefits
-
customer_supports
-
about
-
covered_areas
I tried to use "Page Caching". But in my layout I have a top header that has a condition if user_signed_in?
. So using "Page Caching" doesn't work for me.
Should I use "Fragment Caching" for each partial?
I appreciate any help!
Direct link generation in activeadmin using a text input
I would like to create a quick link text input on the active admin landing page. The idea is that I'd like to create a small form on the dashboard page. The user enters an existing id into the text input and clicks the submit button. Based on the id entered, a direkt link to a resource is generated, based on the resource id entered. The resource is static, so just the id changes. I have no idea if and how that's possible in activeadmin. So I'm more than happy about any suggestions and ideas on a possible implementation.
Css bootstrap form Rails 3.2
I would have the form in the left, but i obtained the form in the right:
I really don't know what is the problem. Probably some Css is in contrast with bootstrap. I would have the text-field
separated (i obtained everything merged) this is the css of my form:
<div class="container">
<div class="row">
<div class="col-sm-12">
<legend>Mr. Sosa:</legend>
</div>
<!-- panel preview -->
<div class="col-sm-5">
<h4>Add payment:</h4>
<div class="panel panel-default">
<div class="panel-body form-horizontal payment-form">
<div class="form-group">
<label for="concept" class="col-sm-3 control-label">Concept</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="concept" name="concept">
</div>
</div>
<div class="form-group">
<label for="description" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="description" name="description">
</div>
</div>
<div class="form-group">
<label for="amount" class="col-sm-3 control-label">Amount</label>
<div class="col-sm-9">
<input type="number" class="form-control" id="amount" name="amount">
</div>
</div>
<div class="form-group">
<label for="status" class="col-sm-3 control-label">Status</label>
<div class="col-sm-9">
<select class="form-control" id="status" name="status">
<option>Paid</option>
<option>Unpaid</option>
</select>
</div>
</div>
<div class="form-group">
<label for="date" class="col-sm-3 control-label">Date</label>
<div class="col-sm-9">
<input type="date" class="form-control" id="date" name="date">
</div>
</div>
</div>
</div>
</div>
Do you have any idea? thank you
How Bootstrap class is loading in my file?
I have not included the Bootstrap file into my view but still class 'btn-default' is working how?
And I am not using any gem for Bootstrap.
Here is the code -
<%= submit_tag "Get Order Details", class: 'btn btn-default' %>
Rails -v command gives me rails isn't installed
However rails -v
command gives me rails isn't installed,i found rails gem in this path /bundle/ruby/1.9.1/gems
Show Tags Of Only The Items In The Category
I have a list of categories. When you click on a category lets say Computers it should only show a tag cloud of the items in that category in this case Computers. Tags from the Mobile Phone category should be showing.
Currently my tag cloud shows all tags across all categories.
How would someone go about showing only the tags inside that category?
Here is my view. Please refer to tag_cloud
<p id="notice"><%= notice %></p>
<div class = "col-md-3">
<h1>
<strong><%= @category.name %></strong>
</h1>
</div>
<div class = "col-md-9">
<div id="tag_cloud">
<% tag_cloud Item.tag_counts, %w[s m l] do |tag, css_class| %>
<%= link_to tag.name, tag_path(tag.name, id: @category.id), class: css_class %>
<% end %>
</div>
</div>
<div class = "col-md-12">
<div class="line-separator"></div>
</div>
<div class = "col-md-12">
<div id="items" class="transitions-enabled">
<% @items.each do |item| %>
<div class="box panel panel-default">
<div class="itemlisttitle"><%= item.title %></div>
<%= link_to image_tag(item.image.url (:medium)), item %>
<div class ="panel-body">
<div class = "itemlistprice">$<%= item.price %></div>
<div class = "itemlistretailer"><%= image_tag item.user.avatar(:thumb) %> Retailer: <%= link_to item.user.username, item.user %></div>
</div>
</div>
<% end %>
</div>
</div>
Routes
Rails.application.routes.draw do
resources :categories
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
resources :users
get 'user_items' => 'users#show_user_items'
root 'items#home'
get 'signup' => 'users#new'
get 'show' => 'users#show'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :items
get 'items_new' => 'items#new'
get 'tags/:tag', to: 'categories#show', as: :tag
Category Controller
class CategoriesController < ApplicationController
before_action :set_category, only: [:show]
before_action :admin_user, only: [:destroy, :index, :edit]
def index
@categories = Category.all
end
def show
if params[:tag]
@items = Item.tagged_with(params[:tag])
else
@items = Item.where(category_id: @category.id).order("created_at DESC")
end
end
def new
@category = Category.new
end
def edit
end
def create
@category = Category.new(category_params)
respond_to do |format|
if @category.save
format.html { redirect_to @category, notice: 'Category was successfully created.' }
format.json { render :show, status: :created, location: @category }
else
format.html { render :new }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @category.update(category_params)
format.html { redirect_to @category, notice: 'Category was successfully updated.' }
format.json { render :show, status: :ok, location: @category }
else
format.html { render :edit }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
def destroy
@category.destroy
respond_to do |format|
format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_category
@category = Category.find(params[:id])
end
def category_params
params.require(:category).permit(:name, :parent_id)
end
# Confirms an admin user.
def admin_user
redirect_to(root_url) unless current_user.try(:admin?)
end
end
lundi 24 août 2015
Rails: Change sass variable from controller and compiles it on production mode
There is scss file contains like this
$header-size = 11;
$main-color = "blue";
header {
font-size: $header-size;
color: $main-color;
}
p { color: $main-color; }
I want to change variable values from rails controller and compile it to make it ready to use.
Is it possible?
Deploy on Puma with nginx/apache
For deploying an application in heroku in Puma application server they say it also deploy on nginx
But some tutorials deploy directly on Puma.
Is it necessary to deploy first on nginx/apache then on Puma?
How can I cut only necessary part of string in RoR?
For exsmple:
I have: new.string-@22/4576/:thisneedtoo.ffgFhhA.pdf?7765trimsAskellYo2212
And I need only: string-@22/4576/:thisneedtoo.ffgFhhA.pdf?
How can I override a default scope in a has_many :through association?
Override to a default scope isn't being persisted (in a useful way) in a has_many :through association.
Here's the relevant stuff from the models:
class User
has_one :invitation
default_scope where(registered: true)
end
class Invitation
belongs_to :user, conditions: { registered: [true, false] }
belongs_to :program
end
class Program
has_many :invitations
has_many :users, through: :invitations
end
Finding users through invitations works as expected.
Invitation.joins(:user)
generates this:
SELECT `invitations`.* FROM `invitations` INNER JOIN `users` ON `users`.`id` = `invitations`.`user_id` AND `users`.`registered` IN (1, 0)
Given this, I'd assume that Program.last.users should find all relevant users, whether registered is true or false. Instead, I get this:
SELECT `users`.* FROM `users` INNER JOIN `invitations` ON `users`.`id` = `invitations`.`user_id` WHERE `users`.`registered` = 1 AND `invitations`.`program_id` = 52 AND (`users`.`registered` IN (1, 0))
This is the SQL I expect. How do I create an association that gives me this?
SELECT `users`.* FROM `users` INNER JOIN `invitations` ON `users`.`id` = `invitations`.`user_id` WHERE `users`.`registered` IN (1, 0) AND `invitations`.`program_id` = 52
More context: I'm using rails 3.1.3, and upgrading rails isn't a viable option before this feature needs to go out. Getting rid of default_scope isn't a thing I can do either.
How I can get a location of response headers for this?
Could please someone tell me, how can I get a location of response headers for rollowing respons? http = Net::HTTP.new "s3.amazonaws.com" response = http.request_head(url)
Legacy SSN encryption returns a blank string on decryption
I have a database containing encrypted SSNs which were encrypted using two different methods. The current implementation encrypts/decrypts without issue, however, attempting to decrypt legacy SSNs will always returns a blank string. Looking through the source control, it appears that they originally encrypted using ActiveSupport::MessageEncryptor#encrypt ActiveSupport::MessageEncryptor#decrypt like so:
Setup:
require 'active_support'
# 128 character hex string for the key
KEY = '11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111'
ENCRYPTOR = ActiveSupport::MessageEncryptor.new(KEY)
Decryption:
# All of the undecryptable SSNs are 50 characters
fake_legacy_encrypted_ssn = 'BVWR7PWl2/kuZ6d75/cnwv==--qMADiBu8XoRqn72tug1zaQ=='
ENCRYPTOR.decrypt(fake_legacy_encrypted_ssn)
#=> ""
Encryption:
# Encrypting an SSN returns a 70 characters string, meaning I'm not using the same encryption method?
fake_ssn = '123456789'
ENCRYPTOR.encrypt(fake_ssn)
#=> "Jz0xBXBIC+Pcb6krjopgNcsLcRPPAYytx8Wgn6snqT8=--6rAk3w58N+vRpmpuSEsTvA=="
I have tried installing previous versions of activesupport to hopefully find a different default encryption method other than aes-128-cbc implemented, but no such luck. Might anyone have any suggestions on how to go about decrypting these old SSN values?
How can I get size of this file by remote link in RoR without downloading?
I have a link, e.g.:
Can I get the size of this pdf without downloading it or this is impossible?
Accepts button in rails application
I have an users model ( cliens and perfomers) and also cliens has an order. Perfomers could accepts this orders and i need to put accept button in show template of order.
<% if current_user.user_type == "perfomer" %>
<% if !@order.order_perfomer_id.nil? %>
<h1><%=@order.order_perfomer_id %>
<% end %>
<%= form_for @order do |f| %>
<%= f.submit "Accept order!", :name =>"accept" %>
<% end %>
<% end %>
And after this i check in controller
def show
if !params[:accept].nil?
@order.order_perfomer_id = current_user.id
end
Yes it doesnt work, because it is a wrong way. Can anyone help with my problem?
Ruby & Phython? Should I learn both? [on hold]
So my question is, would it be beneficial to learn both ruby and python...essentially learning a little bit of both Django and rails? I ask this because there are companies i'd love to intern for but they both require different languages. If I learn both would this make me a strong candidate for many job opportunity's who either use ruby or python or is it a waste of my time?
ex) an internship at Zendesk would require knowledge of ruby/rails.
ex) an internship at google would require knowledge of python.
First attempt at file download does not work. Need to click link twice and it works
I am having a really weird situation and would appreciate any help that can be provided.
My setup is pretty simple. I have an ember app that communicates with a Rails backend. I hit a certain route and a spreadsheet report is generated and placed in the public folder of the rails app. So far so good.
The rails backend then sends a response with the path to the file to the front-end that I place in a href that people can click on to download the file. This is where the weirdness happens. The first time that the link to download is clicked, I get a 404. What's weird is that if I click the link again or copy and paste the url into the address bar, the download works. No matter how I attempt to download the file, the first attempt always fails and all subsequent attempts succeed. I even set it up so that on one click I try to download the file twice and the first attempt fails and the second one works. This is definitely not ideal though.
I have no idea what the issue is and would appreciate any help in this.
Thanks
Ruby on Rails. Engine. Uninitialized constant error on production
I have a rails 3 app that is working locally, I am using a rails engine for a module within my app. When I deploy to the production server I get 404 not found errors to my endpoints, more specifically this error:
ActionController::RoutingError (uninitialized constant Api::V2::QuestionnaireController):
However locally I don't get this error and I have access to this controller and all it's actions. My routes in the main app where I am making the calls is
namespace :api, defaults: {format: "json"} do
namespace :v2 do
resources :questionnaires
Inside my Engine I have inside models/qtn/questionnaire.rb
class Qtn::Questionnaire < ActiveRecord::Base end
and in my controller controllers/questionnaire_controller.rb
class QuestionnairesController < ApplicationController
def index @questionnaires = Qtn::Questionnaire.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @questionnaires }
end
end
end
Could anyone help explain why this works perfectly on localhost but I can not access these endpoints once in production?
How does '::' at the beginning of the class affect scope (ruby/rails)?
I'm working in a large rails project where I have some files:
app/services/my_service/my_action/my_model_2.rb:
module <my_service>
module <my_action>
class <my_model_2>
. . .
if some_var = <my_model>::MY_CONST
if some_Var = ::<my_model>::MY_CONST # <-- what is the difference here?
app/services/my_service/my_action/my_model.rb:
module <my_service>
module <my_action>
class <my_model>
app/services/my_service/my_model.rb:
module <my_service>
class <my_model>
app/models/my_model.rb:
class <my_model> < ActiveRecord::Base
. . .
MY_CONST = "my constant"
What is the difference in my_model_2.rb?
How would I scope correctly to access each of the models from my_model_2.rb?
Note that app/models class name is the same as app/services class name.
Act As Taggable Error
I have tags showing in my category show view. When someone views the Mobile Phones Category they will see tags at the top such as iphone, apple, 16gb, black and ect. When someone clicks on 16gb, it should show every item with 16gb tagged in it.
I've worked on this error for 12 hours and can't fix it.
When someone clicks on a tag i get this error.
ActiveRecord::RecordNotFound in CategoriesController#show
Couldn't find Category with 'id'=
def set_category
@category = Category.find(params[:id])
end
I can't figure out how to fix it?
Im using act_as_taggable gem.
Here is category controller
class CategoriesController < ApplicationController
before_action :set_category, only: [:show]
before_action :admin_user, only: [:destroy, :index, :edit]
def index
@categories = Category.all
end
def show
if params[:tag]
@items = Item.tagged_with(params[:tag])
else
@items = Item.where(category_id: @category.id).order("created_at DESC")
end
end
def new
@category = Category.new
end
def edit
end
def create
@category = Category.new(category_params)
respond_to do |format|
if @category.save
format.html { redirect_to @category, notice: 'Category was successfully created.' }
format.json { render :show, status: :created, location: @category }
else
format.html { render :new }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @category.update(category_params)
format.html { redirect_to @category, notice: 'Category was successfully updated.' }
format.json { render :show, status: :ok, location: @category }
else
format.html { render :edit }
format.json { render json: @category.errors, status: :unprocessable_entity }
end
end
end
def destroy
@category.destroy
respond_to do |format|
format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_category
@category = Category.find(params[:id])
end
def category_params
params.require(:category).permit(:name, :parent_id)
end
# Confirms an admin user.
def admin_user
redirect_to(root_url) unless current_user.try(:admin?)
end
end
Here is my category show view.
<p id="notice"><%= notice %></p>
<div class = "col-md-3">
<h1>
<strong><%= @category.name %></strong>
</h1>
</div>
<div class = "col-md-9">
<div id="tag_cloud">
<% tag_cloud Item.tag_counts, %w[s m l] do |tag, css_class| %>
<%= link_to tag.name, tag_path(tag.name), class: css_class %>
<% end %>
</div>
</div>
<div class = "col-md-12">
<div class="line-separator"></div>
</div>
<div class = "col-md-12">
<div id="items" class="transitions-enabled">
<% @items.each do |item| %>
<div class="box panel panel-default">
<div class="itemlisttitle"><%= item.title %></div>
<%= link_to image_tag(item.image.url (:medium)), item %>
<div class ="panel-body">
<div class = "itemlistprice">$<%= item.price %></div>
<div class = "itemlistretailer"><%= image_tag item.user.avatar(:thumb) %> Retailer: <%= link_to item.user.username, item.user %></div>
</div>
</div>
<% end %>
</div>
</div>
Here is routes. So you can see how the tags are routed.
Rails.application.routes.draw do
resources :categories
get 'password_resets/new'
get 'password_resets/edit'
get 'sessions/new'
resources :users
get 'user_items' => 'users#show_user_items'
root 'items#home'
get 'signup' => 'users#new'
get 'show' => 'users#show'
get 'login' => 'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :items
get 'items_new' => 'items#new'
get 'tags/:tags', to: 'categories#show', as: :tag
Schema.rb
ActiveRecord::Schema.define(version: 20150731101116) do
create_table "categories", force: :cascade do |t|
t.string "name"
t.string "ancestry"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
add_index "categories", ["ancestry"], name: "index_categories_on_ancestry"
create_table "items", force: :cascade do |t|
t.string "title"
t.decimal "price"
t.text "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "user_id"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.integer "category_id"
end
add_index "items", ["user_id", "created_at"], name: "index_items_on_user_id_and_created_at"
add_index "items", ["user_id"], name: "index_items_on_user_id"
create_table "taggings", force: :cascade do |t|
t.integer "tag_id"
t.integer "taggable_id"
t.string "taggable_type"
t.integer "tagger_id"
t.string "tagger_type"
t.string "context", limit: 128
t.datetime "created_at"
end
add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true
add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context"
create_table "tags", force: :cascade do |t|
t.string "name"
t.integer "taggings_count", default: 0
end
add_index "tags", ["name"], name: "index_tags_on_name", unique: true
create_table "users", force: :cascade do |t|
t.string "username"
t.string "email"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "password_digest"
t.string "remember_digest"
t.boolean "admin", default: false
t.string "activation_digest"
t.boolean "activated", default: false
t.datetime "activated_at"
t.string "reset_digest"
t.string ">"
t.datetime "reset_sent_at"
t.string "avatar_file_name"
t.string "avatar_content_type"
t.integer "avatar_file_size"
t.datetime "avatar_updated_at"
t.text "description"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
end