Is there a way to generate a group of routes under an admin scope without having to create a new physical directory (like namespace requires you to).
I know that in Rails 3 there is a scope method on the route mapper, and this appears to do what I want, but apparently it doesn't exist in Rails 2.3.x
My goal is to have a route like this: "/admin/products" map to "app/controllers/products_controller, not "app/controllers/admin/products_controller".
Is there any way to accomplish this in Rails 2.3.x?
Hi all,
I have a Sites table that has columns name, and time. The name does not have to be unique. So for example I may have the entries 'hi.com, 5', 'hi.com, 10', 'bye.com, 4'.
I would like to sum up all the unique sites so that i get 'hi.com, 15' and 'bye.com, 4' for plotting purposes. How can I do that?
(For some reference I was looking at http://railscasts.com/episodes/223-charts but I couldn't get the following (translated to my table) to work
def self.total_on(date)
where("date(purchased_at) = ?", date).sum(:total_price)
end
nor do I really understand the syntax of the 'where("date(purchased_at) = ?", date)' part.
Thanks for helping a rails newbie!
I have a very simple api that is part of a rails app that requires logging in.
I just need a way to make the api part accessible with a simple form that allows the user to enter parameters like a key (just a simple one stored in the DB, no OAuth or anything), a userId to find and return a user via json, and maybe some other parameters like asking for their schedule.
How can I keep this seperate from the rest of the app, making it a public facing form that will grant access only to the api?
Thanks.
I would like to map a relation between two Rails models, where one side can be optionnal. Let's me be more precise...
I have two models: Profile that stores user profile information (name, age,...) and User model that stores user access to the application (email, password,...).
To give you more information, User model is handled by Devise gem for signup/signin.
Here is the scenario of my app:
1/ When a user register, a new row is created in User table and there is an equivalent in Profile table. This leads to the following script:
class User < ActiveRecord::Base
belongs_to :profile
end
2/ A user can create it's profile without registering (kind of public profile with public information), so a row in Profile doesn't have necessarily a User row equivalent (here is the optional relation, the 0..1 relation in UML).
Question: What is the corresponding script to put in class Profile < AR::Base to map optionally with User?
Thanks in advance.
Here I've got two controller methods:
def invite
if request.post?
begin
email = AccountMailer.create_invite(@user,url)
AccountMailer.deliver(email)
flash[:notice] = "Invitation email sent to #{@user.email}"
rescue
#mail delivery failed
flash[:error] = "Failed to deliver invitation"
end
redirect_to :action => :show, :id => @user.id
end
end
and
def show
@title = "User #{@user.full_name}"
end
The problem is, when I send an invitation, and get redirected to ./show, I see no messages at all. If I change redirect_to to render, the message appears. Still, isn't it intended for flash to work in the immediate subsequent requests?
BTW, I'm using Rails+Passenger setup, could it be so that redirected request goes to another application instance?
I'm trying to deploy my first app on Heroku (rails 3). It works fine on my local server, but when I pushed it to Heroku and ran it, it crashes, giving a number of syntax errors. These are related to a collection of scopes I use like the one below:
scope :scored, lambda { |score = nil|
score.nil? ? {} : where('products.votes_count >= ?', score)
}
it produces errors of this form:
"syntax error, unexpected '=', expecting '|' "
"syntax error, unexpected '}', expecting kEND"
Why is this syntax making Heroku choke and how can I correct it? Thanks!
I am using will_paginate for pagination but I can't seem to use more than one condition at a time. For example, if I want to have a sql query that ends in "Where office_id = 5", then it's pretty straight forward, I can do that. but what if I want to do "Where office_id = 5 AND primary_first = 'Mark'"? I can't do that. I have no idea how to enter multiple conditions. Can you help??
Below is an example of my code:
def self.search(search, page, office_id)
paginate :per_page => 5, :page => page,
:conditions => ['office_id', "%#{office_id}"], # + ' and primary_first like ?', "%#{params[:search]}%"],
#:conditions => ['primary_first', "%#{search}%"],
:order => 'created_at'
end
Thank you for your help!
In a form_tag, there is a list of 10 to 15 checkboxes:
<%= check_box_tag 'vehicles[]', car.id %>
How can I select-all (put a tick in every single) checkboxes by RJS? Thanks
EDIT: Sorry I didn't make my question clear. What I meant to ask is how to add a "Select/Un-select All" link in the same page to toggle the checkboxes.
In Rails erb, am using the snippet to show visiting team in a tournament match. How do I get to initially show the current visiting_team? What am I doing wrong?
<%= f.select(:visiting_team_id, Team.all.collect{|t| [t.name, t.id] }) %>
I have two simple models:
class User < ActiveRecord::Base
has_many :tokens
# has_one doesn't work, because Token already stores
# foreign id to user...
# has_one :active_token, :class_name => "Token"
# belongs_to doesn't work because Token belongs to
# User already, and they both can't belong to each other
# belongs_to :active_token, :class_name => "Token"
end
class Token < ActiveRecord::Base
belongs_to :user
end
I want to say "User has_one :active_token, :class_name => 'Token'", but I can't because Token already belongs_to User. What I did instead was just manually add similar functionality to the user like so:
class User < ActiveRecord::Base
has_many :tokens
attr_accessor :active_token
after_create :save_active_token
before_destroy :destroy_active_token
# it belongs_to, but you can't have both belongs_to each other...
def active_token
return nil unless self.active_token_id
@active_token ||= Token.find(self.active_token_id)
end
def active_token=(value)
self.active_token_id = value.id
@active_token = value
end
def save_active_token
self.active_token.user = self
self.active_token.save
end
def destroy_active_token
self.active_token.destroy if self.active_token
end
end
Is there a better way?
I'm using Rails migrations to manage a database schema, and I'm creating a simple table where I'd like to use a non-integer value as the primary key (in particular, a string). To abstract away from my problem, let's say there's a table employees where employees are identified by an alphanumeric string, e.g. "134SNW".
I've tried creating the table in a migration like this:
create_table :employees, {:primary_key => :emp_id} do |t|
t.string :emp_id
t.string :first_name
t.string :last_name
end
What this gives me is what seems like it completely ignored the line t.string :emp_id and went ahead and made it an integer column. Is there some other way to have rails generate the PRIMARY_KEY constraint (I'm using PostgreSQL) for me, without having to write the SQL in an execute call?
NOTE: I know it's not best to use string columns as primary keys, so please no answers just saying to add an integer primary key. I may add one anyway, but this question is still valid.
What's Sinatra's equivalent of Rails' redirect_to method? I need to follow a Post/Redirect/Get flow for a form submission whilst preserving the instance variables that are passed to my view.
Does the redirect method preserve them? (I'm at work at the moment and don't have access to Sinatra to try for myself.)
I used the following in routes to add a new action to my Email controller:
map.resources :emails, :member => { :newfwd => :put}
The expected result was that newfwd_email_path(:id = 1) would generate the following urL: emails/1/newfwd
It does. But I get an error, it treats '1' as an action and 'newfwd' as an id. I want '1' to be interpreted as the id for emails, upon which the newfwd action acts.
I'm not sure what I'm doing wrong. (Note: I am using Rails 2.3.8)
Is it possible in a website search form to enter in series of searches? I have a list of destinations and would like to see if for each destination the search returns a result or throws an error.
I am reading a file that sometimes has chinese and characters of languages other than english.
How can I write a regex that only reads english words/letters?
should it just be /^[a-zA-Z]+/ ?
If I do the above then words like eété will still be picked but I don't want them to be picked:
"été".match(/^[a-zA-Z]+/) => #nil good I didnt want that word
"eété".match(/^[a-zA-Z]+/) => #not nil tricked into picking something i did not want
I'm in a situation where I need to get all articles that are tied to a User through 2 tables:
article_access: gives users privilege to see an article
article_favorites: of public articles, users have favorited these
So in ActiveRecord you might have this:
class User < ActiveRecord::Base
has_many :article_access_tokens
has_many :article_favorites
def articles
unless @articles
ids = article_access_tokens.all(:select => "article_id").map(&:article_id) + article_favorites.all(:select => "article_id").map(&:article_id)
@articles = Article.send(:scoped, :conditions => {:id => ids.uniq})
end
@articles
end
end
That gives me basically an articles association which reads from two separate tables. Question is though, what's the right way to do this?
Can I somehow make 1 SQL SELECT call to do this?
I'm trying to create a perma link for a nested attribute.
For example, look at the links for the answers in SO. I would like to do something similar in rails:
I have Project model with multiple tasks and I would like to create a perma link to a task.
The task can only viewed with the project, just like Q & A on SO.
Ideally, i would do something like:
task_helper.rb:
def GetTaskURL
project = Project.find(:project_id)
return project_url(project,:html) + "#" + id
end
However, i get a method not found. So it seems the only way is to hard-code it:
domain.com url + Projects/show/id.html#task.id
Must be a better way?
Is there an easier way than below to find the longest item in an array?
arr = [
[0,1,2],
[0,1,2,3],
[0,1,2,3,4],
[0,1,2,3]
]
longest_row = []
@rows.each { |row| longest_row = row if row.length > longest_row.length }
p longest_row # => [0,1,2,3,4]
Object.update_attribute(:only_one_field, "Some Value")
Object.update_attributes(:field1 => "value", :field2 => "value2", :field3 => "value3")
Both of these will update an object without having to explicitly tell AR to update.
Rails API says:
for update_attribute
Updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records. The regular update_attribute method in Base is replaced with this when the validations module is mixed in, which it is by default.
for update_attributes
Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will fail and false will be returned.
So if I don't want to have the object validated I should use update_attribute. What if I have this update on a before_save, will it stackoverflow?
My question is does update_attribute also bypass the before save or just the validation.
Also, what is the correct syntax to pass a hash to update_attributes... check out my example at the top.
I have a before filter than calculates a percentage that needs to include the object that is being updated. Is there a one liner in rails that takes care of this?
for example and this is totaly made up:
Object.find(:all, :include = :updated_object)
Currently I'm sending the object that is getting updated to the definition that calculates the percentage and that works but its making things messy.
Let us say I have a model Post which belongs to a User. To convert to json, I do something like this
@reply.to_json(:include => {:user => {:only => [:email, :id]},
:only => [:title, :id])
However, I want to set some defaults for this so I don't have to specify :only everytime. I am trying to override as_json to accomplish this. When I add as_json in User model, it is called when I do @user.to_json but when user is included in @reply.to_json, my overriden as_json for User is ignored.
How do I make this work?
Thanks
I'm using thinking sphinx to for search on a rails app. I have a float field called 'height'. I need to be able to search this field for exact values (i.e. exactly 6.0, not 6.5). I also need to be able to sort on the field.
What I have so far:
indexes height, :sortable => true
Problem:
doesn't sort properly, returns 6.0 and 6.5 if I search for '6'
Hi
I am trying to use a condition on events when the start_at DateTime is equal to or greater than Today's date.
I want to list upcoming events, but clearly they are not upcoming if they have already passed.
I have:
@appointments = Event.find(:all, :conditions => ['move_id = ? AND start_at = ?', @move.id, Date.today])
I think I may be comparing apples and oranges here. It doesn't throw and error, just doesn't do what it is supposed to.
Help! Thanks in advance.