Ruby on rails How to handle validation with has_many relationship

If I leave the author_name as blank then I am getting proper validation error. All good. >> Article.first.comments.create(:body => 'dummy body').errors.full_messages => ["Please enter your name"] Look at this example. >> a = Article.first >> a.comments.create(:body => 'dummy body') >> a.errors.full_messages ["Comments is invalid"] I send instance of article (a in this case) to view layer. I was wondering how do I get access to the pricise error 'please ente

Ruby on rails How to read form-data with ruby

In my controller the result of request.body.read is: ============= --AJAX-----------------------1267183973160 Content-Disposition: form-data; name="1261400603_page_white_word.png"; filename="1261400603_page_white_word.png" Content-Type: application/octet-stream thefile --AJAX-----------------------1267183973160 Content-Disposition: form-data; name="1261400536_page_white_excel.png"; filename="1261400536_page_white_excel.png" Content-Type: application/octet-stream thefile --AJAX----------------

Ruby on rails display error message thrown by ms sql in ruby on rails

i've been looking for a solution for weeks now. yet still failed..i have stored procedure that was called using in ruby on rails..in that stored proc i have validations and thrown using raiserror. ex. raiserror("StartDate must be less than EndDate") in my ruby on rails controller def save begin M.find_by_sql "EXEC spTestProc '3/15/2010', '3/1/2010'" rescue Exception => e render :js => alert(e.message); end but instead i get the error message "StartDate must be less than EndDate", I got

Ruby on rails How link_to mechanism works in Ruby on Rails

I implemented the official Creating the Blog Application project as per the directions given. But I am not getting the idea of link_to used in this project like: <td><%= link_to 'Show', post %></td> <td><%= link_to 'Edit', edit_post_path(post) %></td> <td><%= link_to 'Destroy', post, :confirm => 'Are you sure?', :method => :delete %></td> given in app/views/posts/index.html.erb file, also corresponding code in app/controllers/posts_c

Ruby on rails Payment Page for Rails App

I need to create a page where a user can go in. List the price of an item, the offer price for that item, and then add those two numbers and take a percentage of 15 then take that number and add it to the first two. In Math terms I mean Item Price(5) + Offer(5) + (Item + Offer)*.15 = Total and then from there I will have a checkout page where it will lead them to paypal to make the payment for the total. I think I have an understanding about the paypal part of it but I need help creating a page

Ruby on rails aws-s3 error: AWS::S3::MissingAccessKey error, but keys have been defined?

I'm pretty new to ROR. I've recently deployed an app on heroku and have tried to add an attachment function to the app via paperclip. I've followed all the steps in adding aws-s3 to my app. Here was my initial code: user.rb (model) has_attached_file :avatar, :styles => {:small => "70x70>"}, :storage => :s3, :s3_credentials => "#{RAILS_ROOT}/config/s3.yml", :path => ":attachment/:id/:style/:basename.:ex

Ruby on rails Which mailserver with web interface for Ubuntu + Nginx + Passenger + Ruby on Rails?

I'm running a virtual server with Ubuntu 10.04, Nginx, Phusion Passenger and Ruby on Rails 3. And sending mails via my rails app is no problem, as rails makes it preatty is. But I also want to send and receive mails via a mail client like Outlook, Mail or Thunderbird and I want to a way to manage the mail accounts via a web interface. The most things I found are either too powerful and too pricy (like cPanel with Nginx Support) or they are impossible for me to setup. So, long story short: I'm

Ruby on rails Using rapns on heroku for push notification

I'm using gem rapns (https://github.com/ileitch/rapns) on my rails app. According to rapns doc, I need to run bundle exec rapns to kick start the daemon process which checks database for new notifications to send. So I did following: heroku run bundle exec rapns production --foreground which gave me error: Running bundle exec rapns production --foreground attached to terminal... up, run.3 [WARNING] Detected Rails 3.1.1, patching PostgreSQLAdapter to fix reconnection bug: https:/

Ruby on rails collection.exists? lies to me

In my ruby model I have a has_and_belongs_to_many relation with a model "search": has_and_belongs_to_many :searches I want to add a new search object only if it does not already exists, so I wrote: def append_unless_already_there search unless searches.exists?(search) searches << search end However, adding 2 times a new object passes the condition, and results in a sql exception. Tried replacing search with search.id, but does not change anything. I added some logging to the c

Ruby on rails scale image only width with minimagick in ruby on rails 3

I am using this method for resize the images: version :big do process :resize_to_fit => [560, 200] process :convert => :png end But with this method I have that write a height fixed. I want only scale or resize the width image. I want the height of the image is automatic and scale the image to the width that has been given. How can I scale or resize, only the width image? I'm using minimagick with carrierwave.

Ruby on rails render model to json and use encode64 on one of the model's columns

I am trying to send a model as json. The model has binary data in one of it's columns. For another model I have used format.json {self.encode64(@resource_type.data).to_json} with success, but in that case I only wanted the data column, and not the title etc. What can I do when I want contents from several columns, where only one column's content should be encoded with encode64? In the following code, I don't know where to put the self.encode64 method. format.json { render :json => @reso

Ruby on rails Emberjs + data + rails - Uncaught TypeError: Cannot call method 'map' of undefined

When I am trying to load data from rails db with emberjs + ember data I am getting this error Uncaught TypeError: Cannot call method 'map' of undefined Here's the coffescript code: window.Cosmetics = Ember.Application.create Cosmetics.store = DS.Store.create revision: 4 adapter: DS.RESTAdapter.create bulkCommit: false Cosmetics.admin_user = DS.Model.extend({ name: DS.attr('string') email: DS.attr('string') }); Cosmetics.view = Ember.View.extend templateName: 'ember/views

Ruby on rails rails association has_many_and_belongs_to

I have got two models, User and Event. I need two kind of relationship between User and Event. User (:as organizer) <-------> Event, many to many relationship User (:as attendee) <-------> Event, many to many relationship I am guessing if two different has_many_and_belongs_to association with polymorphism can be used to implement the relations. I am new to rails so I would appreciate any help regarding the problem.

Ruby on rails In Rails, how can I set a cookie's Max-Age?

In Rails 3.2.8, you can write a cookie like this: cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now } The docs say that these are the available option symbols: :value :path :domain :expires :secure :httponly I would expect :max_age to be available as an option too, but perhaps user agent support is not widespread enough yet (?) to warrant including it. So how should I set a cookie's Max-Age in Rails?

Ruby on rails Error with Nested Model Edit page in Rails

I'm tying to perform an edit action on one of my nested models. I keep getting the following error "undefined method `model_name' for NilClass:Class" I don't know what's going on. Any help? Routes resources :users, :except => [ :create, :new ] do resources :store do get "inbox", :on => :collection get "openedmessages", :on => :collection end end Store Actions def edit @store = current_user.store.id end def create @store = current_user.sto

Ruby on rails Error "mail has already been taken" shows up twice on sign up with Security Extension for Devise (RoR)

I am using devise with security extension to validate strong passwords. When I try to registrate an account with an already taken email, I get the error "email has already been taken" twice in the errors hash. My user model looks like this: class User < ActiveRecord::Base # Include default devise modules. Others available are: # :token_authenticatable, :confirmable, # :lockable, :timeoutable and :omniauthable # :trackable deleted devise :database_authenticatable, :registerable, :

Ruby on rails Bundler gives pg when I ask for sqlite3

Any idea what's going on here? How can asking for sqlite3 get me Postgres? My Gemfile has sqlite3 set for development and pg for production, and I'm in the development environment. I've since installed pg manually, which worked once I'd installed libpq-dev, and then after that, bundle show sqlite3 gives me sqlite3 as expected. But how could bundler have got this confused just because a different gem didn't install?

Ruby on rails Ruby on Rails saving multiple instances of a class using a single form for a different class

As a bit of background, I am making a system where registered users can post bounties for artwork. They say what they want and post it as a bounty to be publicly visible. Users may also be registered into the system as artists. But the trick is that the user posting the bounty is allowed to specify a subset of registered artists that are allowed to accept the bounty. I'd guess what I need to make the bounty via a form is the helpful form_for tool... <%= form_for @bounty do |bounty_form| %&g

Ruby on rails Rails has many and belongs to

I am building a daily deal app to better learn Ruby on Rails. On M. Hartly tutorial, I understood the concept of models and their relationship (a microposts belongs_to a user, and a user has_many microposts). However I am not sure how to put that into practice on my daily deal project. I decided to have a Model for users with two type of users with different rights: admin_user who can create/update/edit/delete the deals standard_user who can see the deals and if they find one interesting pa

Ruby on rails Avoiding to hardcode server configuration

I'm working on a Rails application, and I'm about to open-source it. I'm deploying it to a VPS server, configured with nginx and unicorn, following this RailsCast. In order to get Capistrano, Nginx and Unicorn working properly, I had to add some server configuration files in my config/ folder, such as deploy.rb, nginx.conf, unicorn.rb and unicorn_init.sh. I'm working with a git repository, and everything works under the master branch. In other words, Capistrano pull from it to deploy on the s

Ruby on rails Dynamic Custom Field in Template based on client selection

My requirement is making a dynamic custom field in view page. eg:- Customer will have master where they can mention which filed has to show in front-end to users. suppose there is a Customer A they want to show birth-date and Customer B want to show the Age in front-end. This both birth-date and age i have in table but it should visible in front-end based on customer selection. Can anyone help me how we can achieve this in Ruby on Rails. Is that any gem or plug-in available for this. Or is it

Ruby on rails Ruby on Rails CSV upload&import - File name too long

I want to let admins import contacts via csv files into the database. Therefore I am using the ruby csv library and the following code snippet: if request.post? && params[:file].present? inputFile = params[:file].read CSV.foreach(inputFile) do |row| #save row here end end However in CSV.foreach(inputFile) do |row| I get an "Errno::ENAMETOOLONG - File name too long"-error and the error message shows me that it uses the whole csv file as file name. Does anyon

Ruby on rails Instagram.get_access_token returns BadRequest

I'm trying to authenticate a user with Instagram gem. So I have a page with code param returned by instagram, and I only need to send it back with POST request. According to gem documentation I need to do something like: get "/oauth/callback" do response = Instagram.get_access_token(params[:code], :redirect_uri => CALLBACK_URL) session[:access_token] = response.access_token redirect "/feed" end so I have def authenticate response = Instagram.get_access_token(params[:code], :re

Ruby on rails AngularJS + Rails: get a resource but stay on current page

I have a page with a button that will change the state of the resource on the server. Everything is wired up and working fine. But I had to resort to a server response that sent the browser "back" because I don't want to display a new template for the action url. This seems like a typical thing to do: ask the server to do something, then get the current state of the resource and redisplay it in the current template without refetching the template. The markup on the page is like this: <a ng

Ruby on rails Segmentation fault with ruby 2.0.0p247 leading to rails server crashing

Running Rails 4.0, Ruby 2.0.0p247 on OS X Mavericks 1.9 I've encountered an error I've never come across today that I don't understand. When attempting to start my rails server within my project, the server crashes. I did try to reinstall and recompile once, successfully but after successfully running the server twice, it started crashing again. Any idea what could be causing this and a resolution? admins-air:renga admin$ rails s /Users/admin/.rvm/gems/ruby-2.0.0-p247/gems/json-1.8.1/lib/json

Ruby on rails Relationships in Rails

I have models like this: app/models/user.rb class User < ActiveRecord::Base has_many :questions has_many :answers, :through => :questions end app/models/question.rb class Question < ActiveRecord::Base has_many :answers has_many :users end app/models/answer.rb class Answer < ActiveRecord::Base belongs_to :user belongs_to :question attr_accessible :answer, :user_id, :question_id end And a registration form: <%= form_for(resource, :as => resourc

Ruby on rails How to render a form partial in Rails 4?

undefined local variable or method `f' for #<#:0x000001080edfe0> I am trying to render a form within a template page with: <%= form_for @vehicle, html: { class: "f_grp" }, remote: true do |f| %> <%= render "vehicles", locals: { f: f } %> <% end %> The file is loading. But I'm getting an undefined method on f error. Any ideas?

Ruby on rails User model won't update

I try to update an existing user: Controller-Snippet def account_settings @user = current_user end def set_account_info old_user = current_user # verify the current password by creating a new user record. @user = User.authenticate_by_username(old_user.username, params[:user][:password]) # verify if @user.nil? @user = current_user @user.errors[:password] = "Das eingegebene Passwort ist falsch." render :action => "account_settings" else

Ruby on rails Rails Nested attributes with check_box loop

So I have a categories model class Category < ActiveRecord::Base has_many :provider_categories has_many :providers, :through => :provider_categories end and a provider model class Provider < ActiveRecord::Base has_many :provider_categories has_many :categories, :through => :provider_categories accepts_nested_attributes_for :provider_categories, :allow_destroy => true end here is my provider_category model class ProviderCategory < ActiveRecord::Base belongs_to :provider

Ruby on rails Is there a better way to test this Rails controller with RSpec?

I have an Account model that validates that its subdomain is unique. I'm trying to learn how to test controllers with RSpec. Here's what I've come up with, but it's quite different than the generated RSpec test and i'm wondering if this is a good way to test this or if there's a better way. My test: describe "POST create" do describe "with valid params" do it "creates a new Account" do original_count = Account.count account = FactoryGirl.build(:account, :subdomain =

Ruby on rails Regexp UTF-8 with ASCII-8BIT string

I am generating rails' select tags with dynamic values like this: <% @locsprelist = [] %> <% @locationsprelist.each do |t| %> <% @locsprelist.push(Base64.decode64(t[:short_name]), t[:serno]) %> <% end %> and then: select_tag(:quicksearch, options_for_select(@locsprelist)) When I get locations with names in English alphabet, everything is OK, but when there is a location name from another language (for example Georgian: თბილისი), I get an error "incompatible enco

Ruby on rails Sign Up with Devise on Heroku goes to a status=500

I have been trying to troubleshoot this all day I can't get it figured out. I have devise working on development, but when I push to Heroku it doesn't work. When I first push the code, the site will load and I can see the homepage. When I click the login link, I am able to go to the /users/sign_up page. Once I enter in the user details and hit submit I get a page that says "We're sorry, but something went wrong." on the root URL. When I look in heroku console, the user was created. When I de

Ruby on rails Add an Admin Role to the Devise's User Model

I think my question is simple, I followed step by step the second option that appears on this page How To: Add an Admin Role. Now I would like to use current_user.admin? with the before_action method (thus before_action :current_user.admin?), but I see this error. **undefined method `admin?' for :current_user:Symbol** I can't even use the method admin with the before_action method, and if you are wondering, yes, I'm logged. Now, what I can do is define a new method in the controller, such as

Ruby on rails Redirecting after signout

When I sign out, my navigation doesn't change to reflect that I'm signed out until I refresh the page. I set it up like this: <%- if !user_signed_in? %> <li> <%= link_to "Sign up", new_registration_path(:user) %><br /> </li> <li> <%= link_to "Sign in", new_user_session_path %><br /> </li> <% else -%> <li> <%= link_to "Sign Out", destroy_user_session_path(:user), :method => :delete

Ruby on rails Writing valid Excel file

I got an Endpoint that receives emails with .xlsx files as attachments. I want to save these file in my app, so I can later access the data. After receiving the mail and its attachment - which has a mime_type of application/vnd.openxmlformats-officedocument.spreadsheetml.sheet- I call path = "data/emails/#{attachment.filename}" File.write(path, attachment.body.decoded) but I get this error: Encoding::UndefinedConversionError: "\x85" from ASCII-8BIT to UTF-8 When I use add .force_encodi

Ruby on rails How do rails authenticity tokens work? Further clarification needed

I was reading this stackoverflow comment which describes how rails authenticity tokens work: Understanding the Rails Authenticity Token and the highest rated response begins with this: "When the user views a form to create, update, or destroy a resource, the Rails app creates a random authenticity_token, stores this token in the session, and places it in a hidden field in the form. When the user submits the form, Rails looks for the authenticity_token, compares it to the one stored in the s

Ruby on rails Rails 4 / Devise Force User to change password on first login

Im having a weird issue trying to force my users to change their passwords on first login. My server output is telling me it completed the patch successfully, however when I go to log back into the app its still the old password? I'll post output below. But first here is my code to make this happen: #application_controller.rb # Force PW Change On 1st Login def after_sign_in_path_for(resource) if current_user.sign_in_count == 1 edit_passwords_path else

Ruby on rails rails 4 undefined method 'name' for nil:NilClass - category

I want to display an image according to a category name. My images are in the app/assets/images My tutos will have categories that I have created in the console. Now, I have this error (again...) undefined method 'name' for nil:NilClass. Thanks again for your precious help ! here is my form: = simple_form_for @tuto do |f| - if @tuto.errors.any? #error_explanation h2 = "#{pluralize(@tuto.errors.count, "error")} prohibited this tuto from being saved:" ul

Ruby on rails remote rejected master -> master (pre-receive hook declined) heroku

I recieve an error while pushing rails code to heroku. Counting objects: 20, done. Delta compression using up to 4 threads. Compressing objects: 100% (19/19), done. Writing objects: 100% (20/20), 1.75 KiB | 0 bytes/s, done. Total 20 (delta 15), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: ! Could not complete the action. Please try again later. remote: To https://git.heroku.com/dishcuss-api.git ! [remote rejected] master -> master

Ruby on rails Migrations canceled: undefined method `int'

When I run rake db:migrate, show the following error: -- create_table(:posts)<br> rake aborted! StandardError: An error has occurred, all later migrations canceled:`<br> undefined method 'int' for # <ActiveRecord::ConnectionAdapters::MySQL::TableDefinition:0x0055c088b9f520> Did you mean? in? Any ideas or suggestions?

Ruby on rails Second application layout for bilingual Rails site

I have a web site in Spanish, which I need to make an exact copy of into English. However, the navbar labels come from the application controller, which is used for every page on the site. Is it possible to make an application layout which will only be applied to the Spanish pages, and a second application layout for the English pages? I also need a link to ENG and SPA to change between each version. To sum up: Can I make a second application layout? How do I link the new application layout

Ruby on rails CSV Upload in rails

I am trying to add parents and their children data in the parent and child table. I have existing data in these tables and I am trying to add further data and I don't want the data to be repeated. Below is the code I am using to upload data. The child has parent_id. parent.rb has_many :children, dependent: :destroy def self.import(file) CSV.foreach(file.path, headers:true) do |row| parent = Parent.find_or_update_or_create_by( parent_1_firstname: row['parent_1_fir

Ruby on rails How to make columns from joined tables available in Ransack attribute field?

I want to display belongs_to relationship columns in ransackable attributes list. So that I can display them in the dropdown, and perform an advanced search on the (joined) table. How can I do that? Below my model, where each manifest has one consignee. I've adjusted the attribute list, but when I select the consignee name it looks for 'manifest'.'name' and not in 'consignee'.'name' via a JOIN. When I use the simple search form, it works correctly. manifest.rb class Manifest < Application

Ruby on rails How to clean code and eliminate the NoMethodError exception

When a user creates an accounts, the code should allow that user to register a user account through Devise and then create an account, plus a company. The code should redirect to a wizard setup using the wicked gem. Users have roles (rolify) and are authorized with Cancancan. The tables are setup using has_many :through association. This seems to work. The models are as follows: user has_many :accounts_users has_many :accounts, through: :accounts_users, dependent: :destroy has_one

Ruby on rails How to assign User_id to an item

So I have locker model which is just a basic scaffold def change create_table :lockers do |t| t.references :user t.integer :lockerNo t.string :wing t.string :sttatus t.string :comment t.timestamps end end end and also a user model which is just basic devise. I want users to be able to select a locker they want, So I want to list all the lockers and then users click on Select button and then the locker gets assigned to the user i.e the locker_

Ruby on rails How to generate a sequence code string in Rails

I have a model which has a column named code, which is a combination of the model's name column and its ID with leading zeros. name = 'Rocky' id = 16 I have an after_create callback which runs and generates the code: update(code: "#{self.name[0..2].upcase}%.4d" % self.id) The generated code will be: "ROC0016" The code is working. I found (%.4d" % self.id) from another project, but I don't know how it works. How does it determine the number of zeros to be preceded based on the pass

  1    2   3   4   5   6  ... 下一页 最后一页 共 1164 页