There seems to be several technology demos such as http://rails-primer.appspot.com/ on how to run Rails on App Engine. What would be the easiest way to run Rails on App Engine?
I have an entries controller that allows users to add contact information the website. The user-submitted information isn't visible to users until the administrator checks a check box and submits the form. So basically my problem is that if I check the check box as an administrator while initially creating an entry (entries#new) the entry will be publicly visible as expected, but if a non-admin user creates an entry (the normal user view doesn't include the 'live' check box, only the admin one does) then that entry is stuck in limbo because the entries#edit view for some reason doesn't update the boolean check box value when logged in as an admin.
entries#new view:
<% form_for(@entry) do |f| %>
<%= f.error_messages %>
Name<br />
<%= f.text_field :name %>
Mailing Address<br />
<%= f.text_field :address %>
#...
<%- if current_user -%>
<%= f.label :live %><br />
<%= f.check_box :live %>
<%- end -%>
<%= f.submit 'Create' %>
<% end %>
entries#edit (only accessible by admin) view:
<% form_for(@entry) do |f| %>
<%= f.error_messages %>
<%= f.label :name %><br />
<%= f.text_field :name %>
Mailing Address<br />
<%= f.text_field :address %>
<%= f.label :live %><br />
<%= f.check_box :live %>
<%= f.submit 'Update' %>
<% end %>
Any ideas as to why an administrator can't update the :live check box from the edit view?
I would greatly appreciate any suggestions. I'm new to rails. I can post more code if it's needed. Thanks for reading my question.
Does anyone knows how to force WEBrick to process more than one request at a time? I'm using some Ajax on my page for long running database-related tasks and I can clearly see the requests are being processed in a pipeline.
The authlogic rails gem is doing a LOWER in the sql query.
SELECT * FROM `users` WHERE (LOWER(`users`.email) = '[email protected]') LIMIT 1
I want to get rid of the LOWER part since it seems to be slowing down the query by quite a bit.
I'd prefer to just lower the case in the code since this query seems to be expensive.
I'm not sure where to change this behavior in authlogic.
Thanks!
I'm just learning ROR and I came across the if / else statements. I also came across 'elseif' but my text editor (textmate) doesn't pick it up as a keyword, not does the program run properly.
if name == 'Chris'
puts 'What a lovely name.'
elseif name == 'Katy'
puts 'What a lovely name!'
end
I'm using the book, Learn to Program, which was written several years ago. I was wondering if the 'elseif' was changed because when I simply use 'else' it seems to function properly
I would like to create a virtual attribute that will always be included when you do model_instance.inspect. I understand that attr_reader will give me the same thing as just defining an instance method, but I would like this attribute to be part of the object's "make up"
How can I accomplish this?
Thanks!
I have a simple form with text input and text area, but when I submit it the variables seems to be array items instead of just string values?
the form
<%= form_tag(home_kontak_path, :remote => true) do %>
<label>Jou epos adres</label>
<%= text_field(:epos, "", :placeholder => "Jou epos adres", :id => "epos", :class => "input-block-level") %>
<label>Boodskap hier</label>
<%= text_area(:boodskap, "", :rows => "5", :placeholder => "Boodskap hier...", :id => "boodskap", :class => "input-block-level") %>
<%= submit_tag "submit" %>
<% end %>
console output
Started POST "/home/kontak" for 127.0.0.1 at 2012-11-23 11:53:03 +0200
Processing by HomeController#kontak as JS
Parameters: {"utf8"=>"?", "authenticity_token"=>"i+5UWaQeBu7LYGPFBNAbum+67VzyyC82JN2wMlLc/UU=", "epos"=>["text box value"], "boodskap"=>["text area value"], "commit"=>""}
what i would like it to be
instead of
"epos"=["text box value"]
i want it to return
"epos"="text box value"
I have a collection with an index on :created_at (which in this particular case should be a date)
From rails what is the proper way to save an entry and then retrieve it by the date?
I'm trying something like:
Model:
field :created_at, :type = Time
script:
Col.create(:created_at = Time.parse(another_model.created_at).to_s
and
Col.find(:all, :conditions = { :created_at = Time.parse(same thing) })
and it's not returning anything
Yes, I've read and done teh Google many times but I still can't get this working... maybe I'm an idiot :)
I have a system using tickets. Start date is "created_at" in the timestamps. Each ticket closes 7 days after "created_at". In the model, I'm using:
def closes
(self.created_at + 7.days)
end
I'm trying to create another method that will take "closes" and return it as how many days, hours, minutes, and seconds are left before the ticket closes. Anyone want to help and/or admonish my skills? ;)
Hello, I'm looking for any pointers on how to write a rails web app without ActiveRecord.
A doc or an example of a (not too complex) web app using storage backends other than a relational database would be greatly appreciated.
It's not clear on what should be implemented in the model classes in order to make the rails app work without the ActiveRecord layer.
Thanks,
I have an entry.rb model and I'm trying to make a semi-complicated validation. I want it to require one or more of the following fields: phone, phone2, mobile, fax, email or website. How would you write the intended code? Would something like this work?
validates_presence_of :phone and or :phone2 and or :mobile and or :fax and or :email and or :website
So I have made a stripe payment option in my app. When I click the button pay now, it shows me that the payment is successful. and when I go to my stripe account and go to stripe-test and check logs, I can see my test payment with the code 200 OK. But this payment doesn't show in stripe-test events, or in stripe-test payments. Are the payments from logs processed the next day or am I doing something wrong?
def charge
Stripe.api_key = "some_test_api_key"
customer = Stripe::Customer.retrieve(stripe_customer_id)
if stripe_customer_id.nil?
Stripe::Charge.create(
:amount => 2500,
:currency => "cad",
:customer => stripe_customer_id,
:description => "Usage charges for #{name}"
)
end
rescue Stripe::StripeError => e
logger.error "Stripe Error: " + e.message
errors.add :base, "Unable to process charge. #{e.message}."
false
end
Hello, so I have this big method in my application for newsletter distribution. Method is for updating rayons and i need to assigned user to rayon. I have relation n:n through table colporteur_in_rayons witch have attributes since_date and _until_date.
I am junior programmer and i know this code is pretty dummy :)
I appreciated every suggestion.
def update
rayon = Rayon.find(params[:id])
if rayon.update_attributes(params[:rayon])
if params[:user_id] != ""
unless rayon.users.empty?
unless rayon.users.last.id.eql?(params[:user_id])
rayon.colporteur_in_rayons.last.update_attributes(:until_date = Time.now)
Rayon.assign_user(rayon.id,params[:user_id])
flash[:success] = "Rayon #{rayon.name} has been succesuly assigned to #{rayon.actual_user.name}."
return redirect_to rayons_path
end
else
Rayon.assign_user(rayon.id,params[:user_id])
flash[:success] = "Rayon #{rayon.name} has been successfully assigned to #{rayon.actual_user.name}."
return redirect_to rayons_path
end
end
flash[:success] = "Rayon has been successfully updated."
return redirect_to rayons_path
else
flash[:error] = "Rayon has not been updated."
return redirect_to :back
end
end
I have an app that allows a user to create new projects, and the search for them later. One of the options they have when creating a project is giving them start and end dates. At the moment all the code works properly for creating and searching on the dates, but I am now wanting to restrict what dates the user can enter.
I am needing for an error to flag up when the user tries to enter an end date that is before the start date. It's really more for when the user is creating the project. Here is my code so far =
Application.js
//= require jquery
//= require jquery_ujs
//= require jquery-ui
//= require jquery.ui.all
//= require_tree .
$(function() {
$("#project_start_date").datepicker({dateFormat: 'dd-mm-yy'});
});
$(function() {
$("#project_end_date").datepicker({dateFormat: 'dd-mm-yy'});
});
jQuery(function(){
jQuery('#start_date_A').datepicker({dateFormat: "dd-mm-yy"});
});
jQuery(function(){
jQuery('#start_date_B').datepicker({dateFormat: "dd-mm-yy"});
});
New View:
<div class="start_date" STYLE="text-align: left;">
<b>Start Date:</b>
<%= f.text_field :start_date, :class => 'datepicker', :style => 'width: 80px;' %>
</div>
<div class="end_date" STYLE="text-align: left;">
<b>End Date:</b>
<%= f.text_field :end_date, :class => 'datepicker', :style => 'width: 80px;' %>
</div>
Search View:
Start dates between
<%= text_field_tag :start_date_A, params[:start_date_A], :style => 'width: 80px;' %>
-
<%= text_field_tag :start_date_B, params[:start_date_B], :style => 'width: 80px;' %></br>
I tried following examples online to get this to work by doing this in the application.js file:
$(function() {
$("#project_start_date,#project_end_date").datepicker({dateFormat: 'dd-mm-yy'});
});
jQuery(function(){
jQuery('#start_date_A,#start_date_B').datepicker({dateFormat: "dd-mm-yy"});
});
But then the script doesn't run. I am new to rails and javascript so any help at all is appreciated. Thanks in advance.
UPDATE:
Don't know why my question has been voted to be closed. It's quite simple:
I need an error to flag up when the user tries to enter an end date that is before the start date. How can I do that??
I have the following test in my Rails Application:
it "should validate xml" do
builder = Builder::XmlMarkup.new
builder.server(:name => "myServer", :ip => "192.168.1.1").should == "<server name=\"myServer\" ip=\"192.168.1.1\"/>"
end
The problem is that this test passes sometimes, because the order of the xml tag attributes is unpredictable. Is there a way to force this order? Is there any other easy way to build xml?
This example is simplified, I have a big XML. My problem is that I want to do an integration test, which compares a WebService call with a fixed XML file. Otherwise, I would have to parse the xml and verify element by element in the XML.
I have a drop down list of Type in my Products model.
I want to be able to search in the Products index.html.erb so a user selects a type from a drop down list, clicks search and all the products matching that type are returned.
I can get normal search methods working where the user enters in their search in a text box but I cannot get it working when they just select from a dropdown. Can anyone help?
Hello rubyists and railers,
I have a method which checks over a params hash to make sure that it contains certain keys, and to make sure that certain values are set within a certain range. This is for an action that responds to a POST query by an iPhone app.
Anyway, this method is checking for about 10 different conditions - any of which will result in an HTTP error being returned (I'm still considering this, but possibly a 400: bad request error).
My current syntax is basically this (paraphrased):
def invalid_submission_params?(params)
[check one] or
[check two] or
[check three] or
[check four] etc etc
end
Where each of the check statements returns true if that particular parameter check results in an invalid parameter set. I call it as a before filter with params[:submission] as the argument.
This seems a little ugly (all the strung together or statements). Is there a better way? I have tried using case but can't see a way to make it more elegant.
Or, perhaps, is there a rails method that lets me check the incoming params hash for certain conditions before handing control off to my action method?
I have an object which whether validation happens or not should depend on a boolean, or in another way, validation is optional. I haven't found a clean way to do it. What I'm currently doing is this (disclaimer: you cannot unsee, leave this page if you are too sensitive):
def valid?
if perform_validation
super
else
super # Call valid? so that callbacks get called and things like encrypting passwords and generating salt in before_validation actually happen
errors.clear # but then clear the errors
true # and claim ourselves to be valid. This is super hacky!
end
end
Any better ways?
Before you point to the :if argument of many validations, this is for a user model which is using authlogic so it has a lot of validation rules. You can stop reading here if you belive me.
If you don't, authlogic already sets some :ifs like:
:if => :email_changed?
which I have to turn into
:if => Proc.new {|user| user.email_changed? and user.perform_validation}
and in some other cases, since I'm also using authlogic-oid (OpenID) I just don't have control over the :if, authlogic-oid sets it in a way I cannot change it (in time) without further monkey patching. So I have to override seemingly unrelated functions, catch exceptions if a method doesn't exist, etc. The previous hacky solution if the best of my two attempts.
My model class is:
class Category < ActiveRecord::Base
acts_as_nested_set
has_many :children, :foreign_key => "parent_id", :class_name => 'Category'
belongs_to :parent, :foreign_key => "parent_id", :class_name => 'Category'
end
def to_param
slug
end
Is it possible to have such recursive route like this:
/root_category_slug/child_category_slug/child_of_a_child_category_slug ... and so one
Thank you for any help :)
I just got started with rails, and when I testing in development mode, I see in the logs that my Mailer action is taking 1175ms. Is there anyway to find out what exactly is the slow step?
Also, there is a line that says (View:2, DB:1). I assume the DB means number of database lookups, but what about the view?
I know you can do something like:
"SomeWordHere".underscore.gsub("_", " ")
to get "some word here".
I thought that might be a little too much for something so simple. Is there a more efficient way (maybe a built-in method?) to convert "SomeWordHere" to "some word here"?
I'm looking for the best way to write unit test for code that POSTs to an external web service. The body of the POST request is an XML document which describes the actions and data for the web service to perform.
Now, I've wrapped the webservice in its own class (similar to ActiveResource), and I can't see any way to test the exact XML being generated by the class without breaking encapsulation by exposing some of the internal XML generation as public methods on the class. This seems to be a code smell - from the point-of-view of the users of the class, they should not know, nor care, how the class actually implements the web service call, be it with XML, JSON or carrier pigeons.
For an example of the class:
class Resource
def new
#initialize the class
end
def save!
Http.post("http://webservice.com", self.to_xml)
end
private
def to_xml
# returns an XML representation of self
end
end
I want to be able to test the XML generated to ensure it conforms to what the specs for the web service are expecting. So can I best do this, without making to_xml a public method?
I'm using MongoDB as a backend for a Rails app I'm building. Mongo, by default, generates 24-character hexadecimal ids for its records to make sharding easier, so my URLs wind up looking like:
example.com/companies/4b3fc1400de0690bf2000001/employees/4b3ea6e30de0691552000001
Which is not very pretty. I'd like to stick to the Rails url conventions, but also leave these ids as they are in the database. I think a happy compromise would be to compress these hex ids to shorter collections using more characters, so they'd look something like:
example.com/companies/3ewqkvr5nj/employees/9srbsjlb2r
Then in my controller I'd reverse the compression, get the original hex id and use that to look up the record.
My question is, what's the best way to convert these ids back and forth? I'd of course want them to be as short as possible, but also url-safe and simple to convert.
Thanks!
I have been writing specs for controllers and models, but I have never written a helper spec. I have no idea where I start.
I have the following snippet in application_helper.rb
def title(page_title)
content_for(:title) { page_title }
end
How should I write a helper spec on the code?
Also if there's any open-source Rails app to show good helper testing/specing, do let me know.
Trying to create a simple RSS2 Feed that I could later pass on to FeedBurner but can't get RSS feed to display images at all.
Also, from what I have read having xml.instruct! on top might cause IE to complain it's not a valid feed. Is this true?
My Code looks like
xml.instruct!
xml.rss "version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/" do
xml.channel do
xml.title "Store"
xml.link url_for :only_path => false, :controller => 'products'
xml.description "Store"
xml.pubDate @products.first.updated_at.rfc822 if @products.any?
@products.each do |product|
xml.item do
xml.title product.name
xml.pubDate (product.updated_at.rfc822)
xml.image do
xml.url domain_host + product.product_image.url(:small)
xml.title "Store"
xml.link url_for :only_path => false, :controller => 'products'
end
xml.link url_for :only_path => false, :controller => 'products', :action => 'show', :id => product.permalink
xml.description product.fine_print
xml.guid url_for :only_path => false, :controller => 'products', :action => 'show', :id => product.permalink
end
end
end
end