There have been questions with answers on how to write rubygems, but what should you avoid in writing a rubygem? What can cause problems for people using your rubygem?
Is there an easy way to see the actual SQL generated by a rails migration?
I have a situation where a migration to change a column type worked on my local development machine by partially failed on the production server.
My postgreSQL versions are different between local and production (7 on production, 8 on local) so I'm hoping by looking at the SQL generated on the successful migration locally I can work out a SQL statement to run on production to fix things....
Hi Rails'ers,
I encountered some problem while trying to translate my model's names and attributes in a Rails 2.3.5 app.
I have the following model:
class BillingPlan < ActiveRecord::Base
validates_presence_of :billing_option_id
belongs_to :order
belongs_to :user
belongs_to :billing_option
end
When validation fails, my models attributes are translated correctly, but the modelname itself is not. I use the following translation skeleton in de.yml
de:
activerecord:
models:
shipping_plan: "Versandart"
billing_plan: "Rechnungsart"
attributes:
shipping_plan:
shipping_option_id: "Versandoption"
billing_plan:
billing_option_id: "Rechnungsoption"
Basis for my translation file is: http://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/de.yml
Can anyone help?
Thx in advance
J.
G'day guys, I'm currently using fastercsv to construct ActiveRecord elements and I can't for the life of me see this bug (tired), but for some reason when it creates, if in the rake file i output the column I want to save as the element value, it puts out correctly, as either a Trade or a Quote
but when I try to save it into the activerecord, it won't work.
FasterCSV.foreach("input.csv", :headers => true) do |row|
d = DateTime.parse(row[1]+" "+row[2])
offset = Rational(row[3].to_i,24)
o = d.new_offset(offset)
t = Trade.create(
:name => row[0],
:type => row[4],
:time => o,
:price => row[6].to_f,
:volume => row[7].to_i,
:bidprice => row[10].to_f,
:bidsize => row[11].to_i,
:askprice => row[14].to_f,
:asksize => row[15].to_i
)
end
Ideas?
Name and Type are both strings, every other value works except for type. Have I missed something really simple?
Hello
I am trying to DRY up some code by moving some logic into the FormBuilder. After reading the documentation about how to select and alternative form builder the logical solution for me seemed to be something like this.
In the view
<% form_for @event, :builder => TestFormBuilder do |f| %>
<%= f.test %>
<%= f.submit 'Update' %>
<% end %>
and then in app/helpers/application_helper.rb
module ApplicationHelper
class TestFormBuilder < ActionView::Helpers::FormBuilder
def test
puts 'apa'
end
end
end
This, however, gives me an error at the "form_for"
uninitialized constant ActionView::Base::CompiledTemplates::TestFormBuilder
Where am I doing it wrong?
I ultimately want to get data from this page:
http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?trackingNumber=0656887000494793
But that page forwards to:
http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?execution=eXs1
So when I use open (open-uri) to try and fetch the data, it throws a RuntimeError error saying HTTP redirection loop:
So I'm not really sure how to get that data after it redirects and throws that error.
What are the usual problems / stumbling blocks / issues / drawbacks when using a legacy database with a new rails application?
We have to decide between using an old database or writing migration scripts to bring data from old database to new database following rails conventions. What would you suggest?
Hi,
I am getting this error in my terminal when i execute the command above,
Deans-MacBook:depot dean$ rake db:create RAILS_ENV='development'
(in /Users/dean/src/RailsBook/depot) Couldn't create database for {"username"=>"root", "adapter"=>"mysql", "database"=>"depot_development", "host"=>"localhost", "password"=>nil}, charset: utf8, collation: utf8_unicode_ci (if you set the charset manually, make sure you have a matching collation)
In database config file i have the following:
development:
adapter: mysql
database: depot_development
username: root
password:
host: localhost
I have the mysql gem installed and now i am unsure on what to do next. I am running snow leopard on a Macbook. Does anyone know why this error is happening?
Thanks in Advance
Dean
Hello -- Using Application Request Routing I have IIS 7.5 set up as a reverse proxy to a Mongrel service which is serving a rails app. IIS is set up to use Windows Auth and is working but I cannot access the REMOTE_USER variable in the rails app to get at current user's identity. I have inspected the request object in rails and I don't have any other variables like LOGON_USER, HTTP_REMOTE_USER, AUTH_USER, etc. I am trying to find a way to inject the REMOTE_USER variable into Mongrel's server variables. This post describes what I am looking for using mod_rewrite on Apache but I am having trouble recreating this rule for iis.
this is the rewrite rule from the post mentioned above for Apache
RewriteEngine On
RewriteCond %{LA-U:REMOTE_USER} (.+)
RewriteRule . - [E=RU:%1]
Header add X-Forwarded-User %{RU}e
I tried reproducing the rule in IIS and got a URL Rewrite Module error ("The condition's expression "%{LA-U:REMOTE_USER}" is invalid."). I know I'm probably using Apache syntax where IIS syntax is needed but am not sure how to proceed at this point. Any help greatly appreciated.
I have an image that is black text with some gray and pale yellowish background. I basically want to keep the text as black as possible, and make the gray and yellow comparatively lighter...at the very least, turn yellow into a light gray. What's the most efficient way to do that in ImageMagick?
I've just installed this plugin, created the migrations, added everything I needed to make it work(I didn't install ImageMagick yet).
The problem is when I get the upload control parameter to save it in my controller, I get something like this:
#<File:C:\Users\Brian\AppData\Local\Temp\RackMultipart.2560.6677>
instead of a simple string, like
C:\Users\Brian\AppData\Local\Temp\RackMultipart.2560.6677
And if I try to read it I get the following exception:
TypeError backtrace must be Array of
String
What am I doing wrong? How do I read it or simply get rid of the # and < symbols?
I understand the benefit of putting classes, modules, etc. in the lib folder in Rails, but I haven't been able to find a clean way of testing these files. For the most part, it seems like unit tests would be the logical approach.
I guess my question is: What is the "rails way" for testing lib files?
hi,
I had hard time to figure out why I've been getting "unknown action" error message when I was do some editing:
Unknown action
No action responded to 11. Actions: bin, create, destroy, edit, index, new, observe_new, show, tag, update, and vote
you can see that Rails did mention each action in the above list - update. And in my form, I did specify action = "update".
I wonder if some friends could kindly help me with the missing links...
here is the code:
edit.rhtml
<h1>Editing tip</h1>
<% form_tag :action => 'update', :id => @tip do %>
<%= render :partial => 'form' %>
<p>
<%= submit_tag_or_cancel 'Save Changes' %>
</p>
<% end %>
_form.rhtml
<%= error_messages_for :tip %>
<p><label>Title<br/>
<%= text_field :tip, :title %></label></p>
<p><label>Categories<br/>
<%= select_tag('categories[]', options_for_select(Category.find(:all).collect {|c| [c.name, c.id] }, @tip.category_ids), :multiple => true ) %></label></p>
<p><label>Abstract:<br/>
<%= text_field_with_auto_complete :tip, :abstract %></label></p>
<p><label>Name: <br/>
<%= text_field :tip, :name %></label></p>
<p><label>Link: <br/>
<%= text_field :tip, :link %></label></p>
<p><label>Content<br/>
<%= text_area :tip, :content, :rows => 5 %></label></p>
<p><label>Tags <span>(space separated)</span><br/>
<%= text_field_tag 'tags', @tip.tag_list, :size => 40 %></label></p>
class TipsController < ApplicationController
before_filter :authenticate, :except => %w(index show)
# GET /tips
# GET /tips.xml
def index
@tips = Tip.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @tips }
end
end
# GET /tips/1
# GET /tips/1.xml
def show
@tip = Tip.find_by_permalink(params[:permalink])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @tip }
end
end
# GET /tips/new
# GET /tips/new.xml
def new
@tip = session[:tip_draft] || current_user.tips.build
end
def create
#tip = current_user.tips.build(params[:tip])
#tipMail=params[:email]
#if tipMail
# TipMailer.deliver_email_friend(params[:email], params[:name], tip)
# flash[:notice] = 'Your friend has been notified about this tip'
#end
@tip = current_user.tips.build(params[:tip])
@tip.categories << Category.find(params[:categories]) unless params[:categories].blank?
@tip.tag_with(params[:tags]) if params[:tags]
if @tip.save
flash[:notice] = 'Tip was successfully created.'
session[:tip_draft] = nil
redirect_to :action => 'index'
else
render :action => 'new'
end
end
def edit
@tip = Tip.find(params[:id])
end
def update
@tip = Tip.find(params[:id])
respond_to do |format|
if @tip.update_attributes(params[:tip])
flash[:notice] = 'Tip was successfully updated.'
format.html { redirect_to(@tip) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @tip.errors, :status => :unprocessable_entity }
end
end
end
def destroy
@tip = Tip.find(params[:id])
@tip.destroy
respond_to do |format|
format.html { redirect_to(tips_url) }
format.xml { head :ok }
end
end
def observe_new
session[:tip_draft] = current_user.tips.build(params[:tip])
render :nothing => true
end
end
I have Paperclip installed as a gem and i am trying to refresh the thumbnail size of the images. I'm running this command:
rake paperclip:refresh:thumbnails CLASS=User
and receiving this error:
...rake aborted!
The specified key does not exist.
Any ideas?
Finn
I am working on a pretty simple web application (famous last words) and am working with Rails 2.3.5 + MongoMapper 0.7.2 and using embedded documents. I have two questions to ask:
First, are there any example applications out there using Rails + MongoMapper + EmbeddedDocument? Preferably on GitHub or some other similar site so that I can take a look at the source and see where I am supposed to head? If not ...
... what is the best way to approach this task? How would I go about creating a form to handle an embedded document.
What I am attempting to do is add addresses to users. I can toss up the two models in question if you would like.
Thanks for the help!
I am using Maruku with my RoR3 app.
But the problem is that when i use the h(text) method to escape the text from the database before i use Maruku it escapes > to > so Maruku wont see this as a blockquote.
But i still want to escape the rest of the text so my question is how can i make this work?
I don't want to disable the escaping but i don't want it to escape >
I have a bunch of content from the body of one HTML file. How do I put that into the body of a new blank-slate HTML document using Nokogiri? Something like this, but with Nokogiri:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Default Title</title>
</head>
<body class='default-class'>
<%= yield :body %>
</body>
</html>
Hey Guys,
This one might be a little confusing. I'm using AMCharts with rails. Amcharts comes with a PHP script to export images called "export.php"
I'm trying to figure out how to take the code in export.php and put it into a controller.
Here is the code:
<?php
// amcharts.com export to image utility
// set image type (gif/png/jpeg)
$imgtype = 'jpeg';
// set image quality (from 0 to 100, not applicable to gif)
$imgquality = 100;
// get data from $_POST or $_GET ?
$data = &$_POST;
// get image dimensions
$width = (int) $data['width'];
$height = (int) $data['height'];
// create image object
$img = imagecreatetruecolor($width, $height);
// populate image with pixels
for ($y = 0; $y < $height; $y++) {
// innitialize
$x = 0;
// get row data
$row = explode(',', $data['r'.$y]);
// place row pixels
$cnt = sizeof($row);
for ($r = 0; $r < $cnt; $r++) {
// get pixel(s) data
$pixel = explode(':', $row[$r]);
// get color
$pixel[0] = str_pad($pixel[0], 6, '0', STR_PAD_LEFT);
$cr = hexdec(substr($pixel[0], 0, 2));
$cg = hexdec(substr($pixel[0], 2, 2));
$cb = hexdec(substr($pixel[0], 4, 2));
// allocate color
$color = imagecolorallocate($img, $cr, $cg, $cb);
// place repeating pixels
$repeat = isset($pixel[1]) ? (int) $pixel[1] : 1;
for ($c = 0; $c < $repeat; $c++) {
// place pixel
imagesetpixel($img, $x, $y, $color);
// iterate column
$x++;
}
}
}
// set proper content type
header('Content-type: image/'.$imgtype);
header('Content-Disposition: attachment; filename="chart.'.$imgtype.'"');
// stream image
$function = 'image'.$imgtype;
if ($imgtype == 'gif') {
$function($img);
}
else {
$function($img, null, $imgquality);
}
// destroy
imagedestroy($img);
?>
Hi All,
I want to write a named scoped to get a record from its id.
Ex: I have a model called Event and its same as doing Event.find(id) (I dont want to use find inside my controller and I want my controller to use a named scoped (for future flexibility))
So I have written a named scoped
named_scope :from_id, lambda { |id| {:conditions = ['id= ?', id] } }
and I'm calling it from my controller like Event.from_id(id)
But my problems is it returns Event object array not only one object
Ex: if I want to get event name I have to write
event = Event.from_id(id)
event[0].name
instead I want to write
event = Event.from_id(id)
event.name
Am I doing something wrong here..
thanks in advance
cheers
sameera
I don't use RI nor RDOC from the gems I install in my machine or in the servers I handle. (I use other means of documentation)
Every gem I install comes whith ri and rdoc by default and I forget to set --no-ri --no-rdoc.
Is there a way to make those 2 flags default?
I am not really understand how's the nested attributes work in Rails.
I have 2 models, Accounts and Users. Accounts has_many Users. When a new user filled in the form, Rails reported
User(#2164802740) expected, got Array(#2148376200)
Is that Rails cannot read the nested attributes from the form? How can I fix it? How can I save the data from nested attributes form to database?
Thanks all~
Here are the MVCs:
Account Model
class Account < ActiveRecord::Base
has_many :users
accepts_nested_attributes_for :users
validates_presence_of :company_name, :message => "companyname is required."
validates_presence_of :company_website, :message => "website is required."
end
User Model
class User < ActiveRecord::Base
belongs_to :account
validates_presence_of :user_name, :message => "username too short."
validates_presence_of :password, :message => "password too short."
end
Account Controller
class AccountController < ApplicationController
def new
end
def created
end
def create
@account = Account.new(params[:account])
if @account.save
redirect_to :action => "created"
else
flash[:notice] = "error!!!"
render :action => "new"
end
end
end
Account/new View
<h1>Account#new</h1>
<% form_for :account, :url => { :action => "create" } do |f| %>
<% f.fields_for :users do |ff| %>
<p>
<%= ff.label :user_name %><br />
<%= ff.text_field :user_name %>
</p>
<p>
<%= ff.label :password %><br />
<%= ff.password_field :password %>
</p>
<% end %>
<p>
<%= f.label :company_name %><br />
<%= f.text_field :company_name %>
</p>
<p>
<%= f.label :company_website %><br />
<%= f.text_field :company_website %>
</p>
<% end %>
Account Migration
class CreateAccounts < ActiveRecord::Migration
def self.up
create_table :accounts do |t|
t.string :company_name
t.string :company_website
t.timestamps
end
end
def self.down
drop_table :accounts
end
end
User Migration
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :user_name
t.string :password
t.integer :account_id
t.timestamps
end
end
def self.down
drop_table :users
end
end
Thanks everyone. :)
Ok so a friend of mine gave some help with a prototype/obtrusive solution to this but its not quite there. Also, I want to make this unobtrusive instead of using the observe_field function that rails gives me. I don't want to use prototype either because I'm more familiar with JQuery.
Here's my problem: I have an Event that can have multiple ServiceTypes and a ServiceType can belong to many Events. A many-to-many relationship between these two exists as an OfferedService. When creating an event, I have a drop down with a list of TimeAllotments that are something like 10 minutes, 12 minutes, 15 minutes, 20 minutes, 30 minutes etc. When the user selects one of these choices, I want a div tag to be filled with a list of ServiceTypes that are associated with this TimeAllotment. So for example, the user selects "10 minutes" and then the div repopulates with services that last 10 minutes. Here is what I have so far:
... some erb code etc and then
<fieldset>
<legend><%= f.label :time_allotment, "Size of the Appointment Slots:" %></legend>
<div>
<span class="field-group">
<div>
<!-- TimeAllotment is a tabless model which is why this is done like so... -->
<%= select("event_service", "time_allotment", TimeAllotment.all.collect {|ta| [ta.title, ta.value]}, {:prompt => true}) %>
</div>
</span>
</div>
<div style="clear:both;"></div>
Services:
<div>
<span class="field-group">
<!-- this div right here needs to be repopulated when the above select changes. -->
<div id="services">
<% for service_type in ServiceType.all %>
<div>
<%= check_box_tag "event_service[service_type_ids][]", service_type.id, false %>
<%=h service_type.title %>
</div>
<% end %>
</div>
</span>
</div>
<div class="clear"></div>
</fieldset>
ok so right now ALL of the services are there to be chosen from. I want them to change based on what is selected in the combobox event_service_time_allotment.
Can someone help me get pointed in the right direction? I have looked at Ryan's rails casts for using JQuery but its not helpful because he deals with ajax calls for the create action. This would be for the new or edit action. I have a new.js.erb but it doesn't get loaded when calling the new action. I'm super lost as far as getting JQuery to work with my application. I think that if someone can just show me how to make an alert pop up when I change the combo box, and how to return a dataset using ajax the right now, I think I can figure out the rest.
Thanks, I know this is super complicated so any helpful answers will get an upvote.
I'm using the following config:
ActionMailer::Base.smtp_settings = {
:address => "smtp.gmail.com",
:port => 587,
:authentication => :plain,
:enable_starttls_auto => true,
:user_name => "[email protected]",
:password => "sap"
}
When I send the mail, log shows mail is sent. I can see the mail in logger.
But, mail is not delivered to recipient email.
Hello, I am using the http://github.com/collectiveidea/awesome_nested_set awesome nested set plugin and currently, if I choose a sub category as my category_id for an item, I can not search by its parent.
Category.parent
Category.Child
I choose Category.child as the category that my item is in. So now my item has category_id of 4 stored in it.
If I go to a page in my rails application, lets say teh Category page and I am on the Category.parent's page, I want to show products that have category_id's of all the descendants as well.
So ideally i want to have a find method that can take into account the descendants. You can get the descendants of a root by calling root.descendants (a built in plugin method).
How would I go about making it so I can query a find that gets the descendants of a root instead of what its doing now which is binging up nothing unless the product had a specific category_id of the Category.parent.
I hope I am being clear here. I either need to figure out a way to create a find method or named_scope that can query and return an array of objects that have id's corresponding tot he descendants of a root OR if I have any other options, what are they?
I thought about creating a field in my products table like parent_id which can keep track of the parent so i can then create two named scopes one finding the parent stuff and one finding the child stuff and chaining them.
I know I can create a named scope for each child and chain them together for multiple children but this seems a very tedious process and also, if you add more children, you would need to specify more named scopes.
I'm coming from a .NET background, where it is a practice to not bind domain/entity models directly to the view in not-so-basic CRUD-ish applications where the view does not directly project entity fields as-is.
I'm wondering what's the practice in RoR, where the default persistence mechanism is ActiveRecord. I would assert that presentation-related info should not be leaked to the entities, not sure though if this is how real RoR heads would do it.
If DTOs/model per view is the approach, how will you do it in Rails?
Your thoughts?
EDIT:
Some examples:
- A view shows a list of invoices, with the number of unique items in one column.
- A list of credit card accounts, where possibly fraudulent transactions were executed. For that, the UI needs to show this row in red.
For both scenarios, The lists don't show all of the fields of the entities, just a few to show in the list (like invoice #, transaction date, name of the account, the amount of the transaction)
For the invoice example, The invoice entity doesn't have a field "No. of line items" mapped on it. The database has not been denormalized for perf reasons and it will be computed during query time using aggregate functions.
For the credit card accounts example, surely the card transaction entity doesn't have a "Show-in-red" or "IsFraudulent" invariant. Yes it may be a business rule, but for this example, that is a presentation concern, so I would like to keep it out of my domain model.