I want to set the TTL for the keys while creating the connection. Right now I am setting it while writing to the cache. Is there a configuration parameter for this?
Hello
I'm confuse about objects that I can't save, simplified model is
class Subscription < ActiveRecord::base
belongs_to :user, :class_name => "User", :foreign_key => "user_id"
has_many :transactions, :class_name => "SubscriptionTransaction"
validates_presence_of :first_name, :message => "ne peut être vide"
validates_presence_of :last_name, :message => "ne peut être vide"
validates_presence_of :card_number, :message => "ne peut être vide"
validates_presence_of :card_verification, :message => "ne peut être vide"
validates_presence_of :card_type, :message => "ne peut être vide"
validates_presence_of :card_expires_on, :message => "ne peut être vide"
attr_accessor :card_number, :card_verification
validate_on_create :validate_card
def validate_card
unless credit_card.valid?
credit_card.errors.full_messages.each do |message|
errors.add_to_base message
end
end
end
def credit_card
@credit_card ||= ActiveMerchant::Billing::CreditCard.new(
:type => card_type,
:number => card_number,
:verification_value => card_verification,
:month => card_expires_on.month,
:year => card_expires_on.year,
:first_name => first_name,
:last_name => last_name
)
end
end
and in my subscription_controller
if subscription.save
# do something
else
debugger # means breakpoint where i try subscription.errors.full_messages
# do something else
end
I tried to use ruby-debug for this adding a breakpoint before. And subscription.valid? return false which explains that ActiveRecord doesn't allow the save method. Unfortunately i can't know why the object is invalid.
subscription.errors.full_messages # => []
I'm stucked, if you have any idea, thank you.
I have a large collection where I want to modify all the documents by populating a field.
A simple example might be caching the comment count on each post:
class Post
field :comment_count, type: Integer
has_many :comments
end
class Comment
belongs_to :post
end
I can run it in serial with something like:
Post.all.each do |p|
p.udpate_attribute :comment_count, p.comments.count
end
But it's taking 24 hours to run (large collection). I was wondering if mongo's map/reduce could be used for this? But I haven't seen a great example yet.
I imagine you would map off the comments collection and then store the reduced results in the posts collection. Am I on the right track?
If i have two tables Books, CDs with corresponding models.
I want to display to the user a list of books and CDs. I also want to be able to sort this list on common attributes (release date, genre, price, etc.). I also have basic filtering on the common attributes.
The list will be large so I will be using pagination in manage the load.
items = []
items << CD.all(:limit => 20, :page => params[:page], :order => "genre ASC")
items << Book.all(:limit => 20, :page => params[:page], :order => "genre ASC")
re_sort(items,"genre ASC")
Right now I am doing two queries concatenating them and then sorting them. This is very inefficient. Also this breaks down when I use paging and filtering. If I am on page 2 of how do I know what page of each table individual table I am really on? There is no way to determine this information without getting all items from each table.
I have though that if I create a new Class called items that has a one to one relationship with either a Book or CD and do something like
Item.all(:limit => 20, :page => params[:page], :include => [:books, :cds], :order => "genre ASC")
However this gives back an ambiguous error. So can only be refined as
Item.all(:limit => 20, :page => params[:page], :include => [:books, :cds], :order => "books.genre ASC")
And does not interleave the books and CDs in a way that I want.
Any suggestions.
Hi,
I'm working on a rake task which imports from a JSON feed into an ActiveRecord called Person.
Person has quite a few attributes and rather than write lines of code for setting each attribute I'm trying different methods.
The closest I've got is shown below. This works nicely as far as outputing to screen but when I check the values have actually been set on the ActiveRecord itself it's always nil.
So it looks like I can't use .to_sym to solve my problem?
Any suggestions?
I should also mention that I'm just starting out with Ruby, have been doing quite a bit of Objective-c and now need to embrace the Interwebs :)
http = Net::HTTP.new(url.host, url.port)
http.read_timeout = 30
json = http.get(url.to_s).body
parsed = JSON.parse(json)
if parsed.has_key? 'code'
updatePerson = Person.find_or_initialize_by_code(parsed['code'])
puts updatePerson.code
parsed.each do |key, value|
puts "#{key} is #{value}"
symkey = key.to_sym
updatePerson[:symkey] = value.to_s
updatePerson.save
puts "#{key}....." # shows the current key
puts updatePerson[:symkey] # shows the correct value
puts updatePerson.first_name # a sample key, it's returning nil
end
Hi,
I have a single select_tag with categories gathered from array in controller. When the user selects a category I want the application to redirect to the selected category. I have the following code in my view which. (I've tried both using :method = :get and :post, only change is in development.log)
<%=select_tag "cat_selected", options_for_select(@cats_for_mt)%><br>
<%=observe_field 'cat_selected',
:url => {:action => :viewflokkur},
:with => 'cat',
:method => :get %>
When I select one of the options the following gets logged to development.log.
Processing CategoriesController#viewflokkur (for 127.0.0.1 at 2010-06-12 12:33:26) [GET]
Parameters: {"cat"=>"Taugasjúkraþjálfun", "authenticity_token"=> "B2u5ULNr7IJ/ta0+hiAMBjmjEtTtc/yMAQQvSxFn2d0="}
Rendering template within layouts/main
Rendering categories/viewflokkur
Completed in 20ms (View: 18, DB: 0) | 200 OK [http://localhost/categories/viewflokkur?cat=Taugasj%C3%BAkra%C3%BEj%C3%A1lfun&authenticity_token=B2u5ULNr7IJ%2Fta0%2BhiAMBjmjEtTtc%2FyMAQQvSxFn2d0%3D]
According to this I should now be in "viewflokkur", but nothing changes in the browser window. Is there anything else I need to do, maybe in the controller?
BR,
Sindri
I'm developing a real estate web catalogue and want to geocode every ad using geokit gem.
My question is what would be the best database layout from the performance point if i want to make search by country, city of the selected country, administrative area or nearest metro station of the selected city. Available countries, cities, administrative areas and metro sations should be defined by the administrator of catalogue and must be validated by geocoding.
I came up with single table:
create_table "geo_locations", :force => true do |t|
t.integer "geo_location_id" #parent geo location (ex. country is parent geo location of city
t.string "country", :null => false #necessary for any geo location
t.string "city", #not null for city geo location and it's children
t.string "administrative_area" #not null for administrative_area geo location and it's children
t.string "thoroughfare_name" #not null for metro station or street name geo location and it's children
t.string "premise_number" #house number
t.float "lng", :null => false
t.float "lat", :null => false
t.float "bound_sw_lat", :null => false
t.float "bound_sw_lng", :null => false
t.float "bound_ne_lat", :null => false
t.float "bound_ne_lng", :null => false
t.integer "mappable_id"
t.string "mappable_type"
t.string "type" #country, city, administrative area, metro station or address
end
Final geo location is address it contains all neccessary information to put marker of the real estate ad on the map. But i'm still stuck on search functionality.
Any help would be highly appreciated.
I am using Hpricot to parse a theme file. I have noticed, however, that if I feed a valid HTML5 document into Hpricot(), it auto-closes HTML5 tags (like <section>), and messes with the DOCTYPE.
Are there any extensions to Hpricot, or perhaps a flag I need to set, that will allow HTML5 documents to be parsed correctly?
Following this tutorial getting the following errors:
NameError in Admin/dashboardsController#show
uninitialized constant Admin::DashboardsController
NameError in Admin sessionController#new
uninitialized constant Admin::AdminHelper
not sure how to correct this!
I have a collection of recipes, each having a number of ingredients. This information is stored in a join table. Give a recipe, I'd like to find recipes similar to it based on ingredients. How would I go about doing this?
For whatever reason, my cucumber is using my _development db instead of my _test db.
How do I change that?
This is what my database.yml says
test:
adapter: mysql
encoding: utf8
but i get the error database configuration does not specify adapter
Ok, I have been suck on it for hours. I thought net/imap.rb with ruby 1.9 supported the idle command, but not yet.
Can anyone help me in implementing that? From here, I though this would work:
class Net::IMAP
def idle
cmd = "IDLE"
synchronize do
tag = generate_tag
put_string(tag + " " + cmd)
put_string(CRLF)
end
end
def done
cmd = "DONE"
synchronize do
put_string(cmd)
put_string(CRLF)
end
end
end
But imap.idle with that just return nil.
Hi all,
I'm interested in getting a preview functionality working similar to how the 37signals job site does: http://jobs.37signals.com. Below are some screen shots of how it works.
Step 1. Create your ad http://cl.ly/dfc4761b015c7f43c8ab (URL /jobs/new)
Step 2. Preview your ad http://cl.ly/9c4b4041cfea83d8569e (URL /jobs/new/preview)
Step 3. Publish your ad http://cl.ly/a58284d90fd380d2c26b (URL /listings/new/purchase?token=5198)
So assuming you have Post model where Step 1 usually takes place in the new/create view/actions, how should one continue to Step 2 Preview and then after previewing, proceeding to the Step 3 publishing the post/ad?
Do they actually save the ad/post in the database before continuing to Step 2 (Preview) but set a flag (like a boolean field called preview set to true)? It looks like they set a token paramater but I'm not sure what it's used for)
I'm interested in this because it seems to go against the CRUD/REST and I thought it would be good to know how it worked.
Thanks!
How can I translate the following SQL query into a named_scope?
select users.*, sum(total_quantity * total_price) as points_spent
from orders
join users on users.id = orders.user_id
where pay_type = 'points'
group by user_id
order by points_spent desc
Thanks!
I am playing with custom view and routes. I think that I have everything right but obviously not. Essentially I tried to copy the show method and show.html.erb but for some reason it will not work.
My controller
class fatherController < ApplicationController
def show
@father = Father.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @father }
end
end
def ofmine
@father = Father.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @father }
end
end
end
My routes.rb
Parent::Application.routes.draw do
resources :fathers do
resources :kids
end
match 'hospitals/:id/ofmine' => 'father#show2'
end
when I go to
127.0.0.1:/father/1
it works fine but when I try to go to
127.0.0.1:/father/1/ofmine
it gives the following error. It doesn't matter what the variable/method that is called; it occurs at the first one to be displayed. Both show.html.erb and show2.html.erb are the exact same files
My Error from webserver commandline
> Processing by fathersController#show2
> as HTML Parameters: {"id"=>"1"}
> Rendered fathers/show2.html.erb within
> layouts/application (31.6ms) Completed
> in 37ms
>
> ActionView::Template::Error (undefined
> method `name' for nil:NilClass):
> 4: <td>Name</td><td></td>
> 5: </tr>
> 6: <tr>
> 7: <td><%= @father.name %></td><td></td>
> 8: </tr>
> 9: <tr>
> 10: <td>City</td><td>State</td> app/views/fathers/show2.html.erb:7:in
> `_app_views_fatherss_show__html_erb___709193087__616989688_0'
Error as displayed on actual page
NoMethodError in Fathers#show2
Showing
/var/ruby/chs/app/views/fathers/show2.html.erb
where line #7 raised:
undefined method `name' for
nil:NilClass
Extracted source (around line #7):
4: Name 5:
6: 7: <%=
@father.name % 8:
9: 10:
CityState
If anyone could tell me what in the world I am doing wrong I would appreciate it greatly.
What is the best way to set default value in ActiveRecord?
I see a post from Pratik that describes an ugly, complicated chunk of code: http://m.onkey.org/2007/7/24/how-to-set-default-values-in-your-model
class Item < ActiveRecord::Base
def initialize_with_defaults(attrs = nil, &block)
initialize_without_defaults(attrs) do
setter = lambda { |key, value| self.send("#{key.to_s}=", value) unless
!attrs.nil? && attrs.keys.map(&:to_s).include?(key.to_s) }
setter.call('scheduler_type', 'hotseat')
yield self if block_given?
end
end
alias_method_chain :initialize, :defaults
end
YUCK!
I have seen the following examples googling around:
def initialize
super
self.status = ACTIVE unless self.status
end
and
def after_initialize
return unless new_record?
self.status = ACTIVE
end
I've also seen people put it in their migration, but I'd rather see it defined in the model code.
What's the best way to set default value for fields in ActiveRecord model?
I have the following two models:
class Parent < ActiveRecord::Base
has_one :child, dependent: :destroy
validates :child, presence: true
end
class Child < ActiveRecord::Base
belongs_to :parent
validates :parent, presence: true
end
I want to create Parent object.
If I do the following:
Parent.create! or Factory(:parent)
Exception raises: ActiveRecord::RecordInvalid: Validation failed: Child can't be blank
But I can't create Child object without Parent object for the same reason - I need to create Parent object first in order to pass presence validation.
As it appears I have some kind of infinite recursion here.
How to solve it?
Hi folks, i have an urgent problem. Essentially, my routing works on my localhost. But when i deployed this to production, the routes does not seem to work correctly.
For example, given a new route "/invites" - sometimes i will get a 404, and sometimes it will work correctly.
I suspect there is some caching going on somewhere, but i am not sure.
Can someone help?
UPDATE: when a page is not found (when it is supposed to be ok )
Processing UsersController#network
(for 67.180.78.126 at 2010-06-01
09:59:31) [GET] Parameters:
{"id"="new"}
ActionController::RoutingError (No
route matches
"/comm/role_playing_games" with {}):
app/controllers/application_controller.rb:383:in
prev_page_label'
app/controllers/application_controller.rb:238:in
log_timed_info'
app/controllers/users_controller.rb:155:in
network'
app/controllers/users_controller.rb:151:in
network'
app/controllers/application_controller.rb:44:in
turn_on_query_caching'
app/controllers/application_controller.rb:43:in
turn_on_query_caching'
app/controllers/application_controller.rb:42:in
turn_on_query_caching'
app/controllers/application_controller.rb:41:in
turn_on_query_caching'
app/controllers/application_controller.rb:40:in
turn_on_query_caching'
app/controllers/application_controller.rb:39:in
turn_on_query_caching' haml (3.0.6)
lib/sass/plugin/rack.rb:41:in `call'
Rendering
/mnt/app/releases/20100524233313/public/404.html
(404 Not Found)
I use Ultrasphinx gem plugin as a wrapper for accessing Sphinx search daemon.
My model declaration:
class Foo < ActiveRecord::Base
is_indexed :fields => ['content', 'private_notes', 'user_id']
Client code:
filters = {}
if type == "private"
# search only in `content` column
filters['user_id'] = current_user.id
else
# search in `content` and `private_notes` columns
end
results = Ultrasphinx::Search.new(:query => params[:query],
:per_page => 20,
:page => params[:page] || 1,
:filters => filters)
The problem I have now with Ultrasphinx gem(or Sphinx, in general?) is that it does not allow me to change set of fields where to look for matches IN RUNTIME
How can I solve this problem?
This is my code:
[email protected] do |a|
-if @i%3 == 0
%ul
%li=link_to a.name, a
-@i += 1
I need the li to be inside the ul which is inside the if-statement.
I can't do it because of the indentation. Can't I just tell the li to indent automatically?
Thanks
Hello,
I'm trying to prevent a record that has a relationship to another record from being deleted. I can stop the deletion but not send a flash message as I had hoped!
class Purchaseitem < ActiveRecord::Base
before_destroy :check_if_ingredient
...
def check_if_ingredient
i = Ingredient.find(:all, :conditions => "purchaseitem_id = #{self.id}")
if i.length > 0
self.errors.add(:name)
flash.now[:notice] =
"#{self.name} is in use as an ingredient and cannot be deleted"
return false
end
end
This will prevent a the delete wihthout the flash line, and when I add it I get:
undefined local variable or method `flash' for #
Any help would be much appreciated!
I have something like a blog with posts and tags. I want to add email notification functionality - users can subscribe to one or more tags and receive email notifications when new posts are added.
Currently I have a Tag model.
There will be a Subscriber model (containing the user's email)
Do you think I also need a Subscription table where Subscriber and Tag are joined?
.. or I can skip it and directly link Subscriber with Tag?
Hello, I didn't exactly know how to pose this question other than through example...
I have a class we will call Foo. Foo :has_many Bar. Foo has a boolean attribute called randomize that determines the order of the the Bars in the :has_many relationship:
class CreateFoo < ActiveRecord::Migration
def self.up
create_table :foos do |t|
t.string :name
t.boolean :randomize, :default => false
end
end
end
class CreateBar < ActiveRecord::Migration
def self.up
create_table :bars do |t|
t.string :name
t.references :foo
end
end
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
class Foo < ActiveRecord::Base
# this is the line that doesn't work
has_many :bars, :order => self.randomize ? 'RAND()' : 'id'
end
How do I access properties of self in the has_many declaration?
Things I've tried and failed:
creating a method of Foo that returns the correct string
creating a lambda function
crying
Is this possible?
UPDATE
The problem seems to be that the class in :has_many ISN'T of type Foo:
undefined method `randomize' for #<Class:0x1076fbf78>
is one of the errors I get. Note that its a general Class, not a Foo object... Why??
Hi folks, I have a function that is being called more than a thousand times, slowing everything down. However, it is a low level function, and do not know which of my high level function is lopping and making these calls. How can i find out?