i want to use devise gem notification with gritter Posted: 18 Mar 2016 06:57 AM PDT Is that possible to use gritter gem for devise flash messages. format.html { redirect_to @user, notice: 'User was successfully signin.' } help me to do this. thank you. |
Rails form return false works using .submit() but not .on() Posted: 18 Mar 2016 06:45 AM PDT I want to submit a form with ajax, so I'm trying to disable its submission with return false; . When I use $('#post_form').submit(function() { return false; works fine. So what's the problem? Well, I don't want to bind to the #post_form . I want to use: $(document).on('submit', '#post_form', function(e) { But return false; doesn't work. e.preventDefault(); completely fails too. What's going on?? <%= f.button( :submit, name: "Post", title: "Post", class: 'btn btn-default btn-xs notice_submit', id: 'postbutt' ) do %> <span class="glyphicon glyphicon-ok" aria-hidden="true"></span> <% end %> Javascript: $(document).on('submit', '#post_form', function(e) { // return false; doesn't work // $('#post_form').submit(function() { // return false; works fine if ( validatePostForm() ) { $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'script' }); } e.preventDefault(); // this doesn't do anything return false; // neither does this }); |
HTTP Token: Access denied Posted: 18 Mar 2016 06:46 AM PDT i m getting message "**HTTP Token: Access denied** " when access via browser http://localhost:3000/api/v1/tasks.json?auth_token=szVkqLnUbdzbekV8B-n_ but when i access from terminal that's working on success curl http://localhost:3000/api/v1/moments.json -H 'Authorization: Token token="szVkqLnUbdzbekV8B-n_"' here code class Api::V1::TaskController < ApplicationController before_action :autentifikasi def index @tasks = current_user.tasks end private def autentifikasi authenticate_or_request_with_http_token('Premium') do |token, options| @current_user = User.find_by(authentication_token: token) end end end end anybody help me please !! what's wrong with my code ? |
rails, javascript, moment.js converting time formats Posted: 18 Mar 2016 06:29 AM PDT I have a rails4 app. Users can update form via AJAX with bootstrap modal and datetimepicker. To look nice I format the rails time with the help of moment.js. So the process: User clicks, modal pops up and moment.js formats and displays the time. User picks new time and submits the form and on submitting datetime gets converted back and saved to the db. If I use the getter-setter method as you can see below, then displaying the datetime to the user works fine (moment.js transforms UTC to local), but on submitting the form the app doesn't save the new datetime, but keeps the old. If I do it without the getter-setter then the moment.js can't properly format the data , so displaying will be happening in UTC always, but after choosing new date and submitting the form the data gets saved properly into the db. As I see there are 2 solutions, but I couldn't figure it out. Doing without getter-setter, but somehow converting the datetime format with js for moment.js to be able to display it. As I mentioned saving to db works fine since setter method doesn't screw things up. Doing with getter-setter. Thanks to the getter method moment.js can display the datetime well, but the setter method screws things up. So setter method must be changed maybe alongside with the js that submits the form. Can anybody help with this? form: <div class="field form-group"> <%= f.label :deadline_string %> <%= f.text_field :deadline_string, class: "form-control edit-task-deadline" %> </div> getter setter in model def deadline_string deadline.to_datetime.iso8601 end def deadline_string=(deadline_str) self.deadline = deadline_str.strftime('%FT%T') #I also tried with DateTime.parse(deadline_str) end js for displaying momentjs formatted time in form $(document).on('shown.bs.modal', '.updatetask', function (e) { var taskId = $(this).find('.edit-task-submit').data('taskid'); var deadlineField = $(".task_form_" + taskId).closest('.updatetask').find($('.edit-task-deadline')); var deadlineValue = deadlineField.attr('value'); var momentDeadline = moment(deadlineValue).format('MM/DD/YYYY hh:mm A'); deadlineField.val(momentDeadline); }); js for converting back to RoR on submitting form: $(document).on('click', '.edit-task-submit', function (e){ e.preventDefault(); var taskId = $(this).data('taskid'); var deadlineField = $(".task_form_" + taskId).closest('.updatetask').find($('.edit-task-deadline')); var localMoment = moment(deadlineField.val()); deadlineField.val(localMoment.toISOString()); $(".task_form_" + taskId).submit(); }); |
How to link post to topic? Posted: 18 Mar 2016 06:59 AM PDT I made a latest posts box in my app at the root. In this box I have post which belongs to topic. Maybe its a stupid question but how can I redirect click on post to the topic where it belongs? This redirects me to localhost:3000/topics, how to add topic_id's to this path? This is how I get the latest posts: controller: class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :configure_permitted_parameters, if: :devise_controller? helper_method :latest_posts def latest_posts @posts ||= Post.all.order("created_at desc").limit(3) end end index: <% latest_posts.each do |posts| %> <div class="bs-callout bs-callout-warning"> <p><%= link_to post.content.html_safe, topic_path(post.topic) %></p> </div> <% end %> routes.rb: devise_for :users get 'categories' => 'categories#index' resources :topics resources :posts resources :users Routes: new_user_session GET /users/sign_in(.:format) devise/sessions#new user_session POST /users/sign_in(.:format) devise/sessions#create destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy user_password POST /users/password(.:format) devise/passwords#create new_user_password GET /users/password/new(.:format) devise/passwords#new edit_user_password GET /users/password/edit(.:format) devise/passwords#edit PATCH /users/password(.:format) devise/passwords#update PUT /users/password(.:format) devise/passwords#update cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel user_registration POST /users(.:format) devise/registrations#create new_user_registration GET /users/sign_up(.:format) devise/registrations#new edit_user_registration GET /users/edit(.:format) devise/registrations#edit PATCH /users(.:format) devise/registrations#update PUT /users(.:format) devise/registrations#update DELETE /users(.:format) devise/registrations#destroy categories GET /categories(.:format) categories#index topics GET /topics(.:format) topics#index POST /topics(.:format) topics#create new_topic GET /topics/new(.:format) topics#new edit_topic GET /topics/:id/edit(.:format) topics#edit topic GET /topics/:id(.:format) topics#show PATCH /topics/:id(.:format) topics#update PUT /topics/:id(.:format) topics#update DELETE /topics/:id(.:format) topics#destroy posts GET /posts(.:format) posts#index POST /posts(.:format) posts#create new_post GET /posts/new(.:format) posts#new edit_post GET /posts/:id/edit(.:format) posts#edit post GET /posts/:id(.:format) posts#show PATCH /posts/:id(.:format) posts#update PUT /posts/:id(.:format) posts#update DELETE /posts/:id(.:format) posts#destroy users GET /users(.:format) users#index POST /users(.:format) users#create new_user GET /users/new(.:format) users#new edit_user GET /users/:id/edit(.:format) users#edit user GET /users/:id(.:format) users#show PATCH /users/:id(.:format) users#update PUT /users/:id(.:format) users#update DELETE /users/:id(.:format) users#destroy root GET / categories#index |
Paperclip throwing http 500 error log is not showing a clear reason Posted: 18 Mar 2016 05:55 AM PDT I have a rails application which uses paperclip. It all works absolutely fine on my development environment however when I flip over to staging it always throws an error during processing of an uploaded image. I am using paperclip gem version : * paperclip (4.3.1 37589f9) and I have an understanding that paperclip relies on cocaine, I have version : * cocaine (0.5.8) This is the log from the application: I, [2016-03-18T11:57:30.452279 #11506] INFO -- : Started POST "/seller_profile" for 185.14.209.183 at 2016-03-18 11:57:30 +0000 I, [2016-03-18T11:57:30.459696 #11506] INFO -- : Processing by SellerProfileController#create as HTML I, [2016-03-18T11:57:30.460475 #11506] INFO -- : Parameters: {"utf8"=>"✓", "authenticity_token"=>"7WygT7YwDzum+KaH5o7EHV/G2JM1PYkVCrobkh6yRGCoIQcGOMpPYxgvB+uB/7lUzJOzmJioqfmkbGcr6cIgqA==", "seller_profile"=>{"business_logo"=>#<ActionDispatch::Http::UploadedFile:0xbb075fb0 @tempfile=#<Tempfile:/tmp/RackMultipart20160318-11506-euc8vw.jpg>, @original_filename="me.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"seller_profile[business_logo]\"; filename=\"me.jpg\"\r\nContent-Type: image/jpeg\r\n">, "business_name"=>"dasasdasdasd", "business_email"=>"sdaasda@adsads.com", "business_phone_number"=>"231212312", "business_description"=>"wqwwdewqddqwdwdqwqwd", "business_facebook_url"=>"", "business_twitter_url"=>"", "business_instagram_url"=>"", "business_pinterest_url"=>""}, "commit"=>"CREATE AN ACTIVITY"} I, [2016-03-18T11:57:30.495504 #11506] INFO -- : Command :: PATH=/usr/local/bin/:$PATH; file -b --mime '/tmp/ab86a1e1ef70dff97959067b723c5c2420160318-11506-12o3bwp.jpg' I, [2016-03-18T11:57:30.667563 #11506] INFO -- : Command :: PATH=/usr/local/bin/:$PATH; identify -format '%wx%h,%[exif:orientation]' '/tmp/ab86a1e1ef70dff97959067b723c5c2420160318-11506-h4g1qj.jpg[0]' 2>/dev/null I, [2016-03-18T11:57:31.028495 #11506] INFO -- : Completed 500 Internal Server Error in 567ms (ActiveRecord: 0.0ms) I, [2016-03-18T11:57:31.433251 #11506] INFO -- : Rendered /opt/www/clazzoo/shared/bundle/ruby/2.2.0/gems/exception_notification-4.1.4/lib/exception_notifier/views/exception_notifier/_request.text.erb (7.1ms) I, [2016-03-18T11:57:31.443776 #11506] INFO -- : Rendered /opt/www/clazzoo/shared/bundle/ruby/2.2.0/gems/exception_notification-4.1.4/lib/exception_notifier/views/exception_notifier/_title.text.erb (2.6ms) I, [2016-03-18T11:57:31.458817 #11506] INFO -- : Rendered /opt/www/clazzoo/shared/bundle/ruby/2.2.0/gems/exception_notification-4.1.4/lib/exception_notifier/views/exception_notifier/_session.text.erb (6.4ms) I, [2016-03-18T11:57:31.460334 #11506] INFO -- : Rendered /opt/www/clazzoo/shared/bundle/ruby/2.2.0/gems/exception_notification-4.1.4/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.4ms) I, [2016-03-18T11:57:31.485219 #11506] INFO -- : Rendered /opt/www/clazzoo/shared/bundle/ruby/2.2.0/gems/exception_notification-4.1.4/lib/exception_notifier/views/exception_notifier/_environment.text.erb (16.3ms) I, [2016-03-18T11:57:31.486683 #11506] INFO -- : Rendered /opt/www/clazzoo/shared/bundle/ruby/2.2.0/gems/exception_notification-4.1.4/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.4ms) I, [2016-03-18T11:57:31.499245 #11506] INFO -- : Rendered /opt/www/clazzoo/shared/bundle/ruby/2.2.0/gems/exception_notification-4.1.4/lib/exception_notifier/views/exception_notifier/_backtrace.text.erb (1.9ms) I, [2016-03-18T11:57:31.500534 #11506] INFO -- : Rendered /opt/www/clazzoo/shared/bundle/ruby/2.2.0/gems/exception_notification-4.1.4/lib/exception_notifier/views/exception_notifier/_title.text.erb (0.3ms) I, [2016-03-18T11:57:31.501638 #11506] INFO -- : Rendered /opt/www/clazzoo/shared/bundle/ruby/2.2.0/gems/exception_notification-4.1.4/lib/exception_notifier/views/exception_notifier/exception_notification.text.erb (87.9ms) Interestingly, when I run the command which is right before the HTTP 500 manually: identify -format '%wx%h,%[exif:orientation]' '/tmp/ab86a1e1ef70dff97959067b723c5c2420160318-11506-h4g1qj.jpg[0]' I get : 388x345 Which kind of suggests this is all ok! ImageMagick is installed on my machine (Ubuntu 15.04) and is version: Version: ImageMagick 6.8.9-9 Q16 i686 2015-01-06 http://www.imagemagick.org Copyright: Copyright (C) 1999-2014 ImageMagick Studio LLC Features: DPC Modules OpenMP Delegates: bzlib djvu fftw fontconfig freetype jbig jng jpeg lcms lqr ltdl lzma openexr pangocairo png tiff wmf x xml zlib My paperclip config is as follows: Paperclip.options[:command_path] = "/usr/local/bin/" PAPERCLIP_STORAGE_OPTS = { :styles => { :thumb => '100x100!#', :medium => '450x300!>', :large => '600x400!>', :desktop => '750x300!>'}, :convert_options => { :all => '-quality 100' }, :processor => [ :cropper ], :default_url => 'business.jpg' } Paperclip.options[:log] = true Paperclip.options[:log_command] = true Please can somebody help out! |
ActiveRecord where statement selecting fields from nested objects Posted: 18 Mar 2016 06:53 AM PDT Given class Foo has_many :bar end class Bar belongs_to :foo end I want: => #<ActiveRecord::Relation [#<Foo id: 11, qux: 'hi', bar_id: 1, bar_name: 'blah', bar_something: 'blahblah' >, #<Foo id: 23, qux: 'hi', bar_id: 2, bar_name: 'lorem', bar_something: 'ipsum' >]> I can do this: > Foo.where(qux: 'hi').includes(:bar) => #<ActiveRecord::Relation [#<Foo id: 11, qux: 'hi', bar_id: 1 >, #<Foo id: 23, qux: 'hi', bar_id: 2 >]> But it does not load the child records. It seems just to hold on to it in case it's needed. There must be something more elegant than this? Foo.where(qux: 'hi').includes(:bar).to_a.map do | f | f.keys.each { |k| f[ k.to_s ] = f.delete(k) if k.class == :symbol } Bar.column_names.except('id','foo_id').each do | ba | ba_name = 'bar_' + ba f.merge({ba_name => f.bar.send(ba.to_sym)}) end f end |
Toggle on remote link Posted: 18 Mar 2016 06:13 AM PDT I have a link which retrieves data and shows all details, which works fine. However, I want it to act like a toggle, where it removes the details after a second click. It also should not send the ajax request to the server. Maybe some state should be saved to know to either show the details or remove them? What is the best way to do this? This is the link: = link_to "details", testitemlogs_path(testitem_id: testitem.id), remote: true |
Having Trouble Reading Params in Rails Posted: 18 Mar 2016 06:02 AM PDT I'm working on a project that has the following models: storyboards has many frames frames has one of each puzzles and scenes scenes puzzles I have it set so that frames exist in association with a storyboard, however i have both puzzles and scenes existing separately. I want to create both scenes and puzzles separately, and then assign them to a frame when a frame is created. In the new form for frames, I have two collections, one for puzzles and one for scenes. I want to be able to take the selected item, look up that item, and save a reference to the frame number in the appropriate scene/puzzle table. However, I keep getting a blank parameter. My controller code is as follows: class FramesController < ApplicationController before_action :set_storyboard before_action :set_frame, only: [:show, :edit, :update, :destroy] def new @frame = @storyboard.frames.build @puzzles = Puzzle.all @scenes = Scene.all end def create puts params.inspect @frame = @storyboard.frames.build(frame_params) @puzzle = Puzzle.find(frame_params[:puzzle]) if @frame.save flash[:notice] = "Frame has been created." redirect_to [@storyboard, @frame] else flash.now[:alert] = "Frame has not been created." render "new" end end def show end private def set_storyboard @storyboard = Storyboard.find(params[:storyboard_id]) end def frame_params params.require(:frame).permit(:frame_order) end def set_frame @frame = @storyboard.frames.find(params[:id]) end end It's not complete as I am not trying to locate the scenes yet, I'm trying to get the puzzle lookup working first. The params that are showing in WEBrick are as follows: Started POST "/storyboards/2/frames" for 127.0.0.1 at 2016-03-18 06:33:13 -0500 Processing by FramesController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"8KUEIEa7jVS2BsRFby8Cn8Hb0R5LM+paCNbKbfL5ielq01Q7IJlA3HtZX9+pLmYSPhRJq6xlhU2bR7umbv1T+w==", "frame"=>{"frame_order"=>"1", "scene"=>"2", "puzzle"=>"1"}, "commit"=>"Create Frame", "storyboard_id"=>"2"} My _form.html.erb is as follows: <%= simple_form_for([storyboard, frame]) do |f| %> <%= f.input :frame_order, label: "Frame Order" %> <%= f.input :scene, collection: @scenes %> <%= f.input :puzzle, collection: @puzzles %> <%= f.button :submit, class: "btn-primary" %> The error that I am getting is as follows: Failure/Error: @puzzle = Puzzle.find(frame_params[:puzzle]) ActiveRecord::RecordNotFound: Couldn't find Puzzle with 'id'= I thought that it might be since I'm using strong params, but if I add scene and puzzle to the frame_params, I also get an error on the create method as follows: Failure/Error: @frame = @storyboard.frames.build(frame_params) ActiveRecord::AssociationTypeMismatch: Scene(#50941880) expected, got String(#6701160) From what I've been able to lookup, using params[:frame][:puzzle] should work and should give me a value of 1, but instead I'm getting nothing. I'm not sure what I've done wrong. Any assistance or advice would be greatly appreciated. Thanks! |
get an error Unexpected exit code while installing Java: 127 (RuntimeError) while ruboto setup Posted: 18 Mar 2016 04:55 AM PDT I have installed ruboto gem successfully then when I use ruboto setup it is throwing below error. it is installing jdk and throwing the error Unexpected exit code while installing Java C:\Sites>ruboto setup -y DL is deprecated, please use Fiddle For a better pry experience, please use ansicon: http://adoxa.3eeweb.com/ansicon/ WARN: Unresolved specs during Gem::Specification.reset: rake (~> 10.0) rubyzip (~> 1.0) WARN: Clearing out unresolved specs. Please report a bug if this causes problems. Java runtime : Found Java Compiler : Not found Apache ANT : Not found Android Package Installer: Not found Android Emulator : Not found Intel HAXM : Not found Android SDK Command adb : Not found Android SDK Command dx : Not found Platform SDK android-16 : Not found !!! Ruboto setup is NOT OK !!! Java JDK was not found. Downloading... Following redirect to https://edelivery.oracle.com/otn-pub/java/jdk/7/jdk-7-windows-x64.exe Following redirect to http://download.oracle.com/errors/download-fail-1505220.html Installing jdk-7-windows-x64.exe... F, [2016-03-18T17:22:04.636746 #9192] FATAL -- : Unexpected exit code while installing Java: 127 (RuntimeError) C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/ruboto-1.4.1/lib/ruboto/util/setup.rb:386:in `install_java' C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/ruboto-1.4.1/lib/ruboto/util/setup.rb:304:in `install_all' C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/ruboto-1.4.1/lib/ruboto/util/setup.rb:24:in `setup_ruboto' C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/ruboto-1.4.1/lib/ruboto/commands/base.rb:467:in `run' C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/main-5.3.2/lib/main/program/class_methods.rb:155:in `block in run' C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/main-5.3.2/lib/main/program/class_methods.rb:144:in `catch' C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/main-5.3.2/lib/main/program/class_methods.rb:144:in `run' C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/main-5.3.2/lib/main/factories.rb:18:in `run' C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/main-5.3.2/lib/main/factories.rb:25:in `Main' C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/ruboto-1.4.1/lib/ruboto/commands/base.rb:28:in `main' C:/RailsInstaller/Ruby2.1.0/lib/ruby/gems/2.1.0/gems/ruboto-1.4.1/bin/ruboto:11:in `<top (required)>' C:/RailsInstaller/Ruby2.1.0/bin/ruboto:23:in `load' C:/RailsInstaller/Ruby2.1.0/bin/ruboto:23:in `<main>' |
Check if user has provided image? Posted: 18 Mar 2016 05:55 AM PDT I am using these gem's to handle my image uploader: gem 'carrierwave' gem 'mini_magick' gem 'fog' However I can't seem to find out whether or not the image is nil or empty, as it can't be because it returns this when I call @user.picture: "********@hotmail.co.uk", encrypted_password: "************************************", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 6, current_sign_in_at: "2016-03-18 11:23:00", last_sign_in_at: "2016-03-18 11:18:16", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2016-03-17 15:00:46", updated_at: "2016-03-18 11:24:13", provider: nil, uid: nil, username: "StormViper", login: nil, cart_id: 1, admin: true, picture: "download.jpg", brand_id: 1, is_brand?: true>, @mounted_as=:picture, @storage=#>, @file=#, @versions={}> This is my user controller: if @user.save p "USER SAVED LOGIN: #{@user.username}" @cart = Cart.create(:user_id => @user.id, :cart_count => 0) @cart.save @user.cart_id = @cart.id @user.save @slot = Slot.create(:cart_id => @cart.id) @slot.save @cart.slot_id = @slot.id @cart.save redirect_to root_path else p "USER FAILED LOGIN: #{@user.username}" render 'new' end How would I solve this issue? I can't directly change the picture.url as it returns: *** NoMethodError Exception: undefined method `url=' for PictureUploader:0x007f73e6135e78> My user model contains: class User < ActiveRecord::Base has_one :cart has_many :slots, through: :carts belongs_to :brand # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable attr_accessor :login devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login] validates :username, presence: true, uniqueness: true def self.find_for_database_authentication(warden_conditions) conditions = warden_conditions.dup if login = conditions.delete(:login) where(conditions.to_hash).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first elsif conditions.has_key?(:username) || conditions.has_key?(:email) where(conditions.to_hash).first end end mount_uploader :picture, PictureUploader end |
Rails and Solr: Return multiple models in the search results Posted: 18 Mar 2016 04:45 AM PDT I have a 'Buck' model which has_many 'buck_details'. I run search through bucks including buck_details as well. So the search returns results that contain only bucks objects. bucks = Buck.search(:include => [:buck_details]) do .... Now when I do bucks.results, it returns only buck_details objects. I, however have to run bucks.joins(:buck_details) at some other place and this includes all buck_details associated with the searched bucks. What I wanted was to get those buck_details filtered in the initial solr search while searching bucks. How do I go about it? |
Has_many association mapped to different model Posted: 18 Mar 2016 06:43 AM PDT I want users to be able to select the languages they speak. I have setup the associations, the table attributes and the part of the form. When I select a language and submit the form I go to the rails console and do a u.languages but I get an empty array back: => [] Here are the logs when I submit the form: Started POST "/update_user_via_user" for 127.0.0.1 at 2016-03-18 13:26:03 +0200 ActiveRecord::SchemaMigration Load (0.4ms) SELECT "schema_migrations".* FROM "schema_migrations" Processing by UsersController#update_user_via_user as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"CB1Qca0VrBcap9qO6VpKfoi2dG8GNG+tGGNDgCnFEv4E=", "user"=>{ "fullname"=>"John Doe", "languages"=>["", "1", "2"]}, "commit"=>"Save"} User Load (28.6ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 ORDER BY "users"."id" ASC LIMIT 1 Unpermitted parameters: languages (0.1ms) begin transaction (0.1ms) commit transaction Redirected to http://127.0.0.1:3000/setup_profile Completed 302 Found in 163ms (ActiveRecord: 29.5ms) Now if you look closely on the loogs you will see "Unpermitted parameters: languages". In my users_controller I have the followings: def user_params params.require(:user).permit(:languages, :fullname) end and the custom action: def update_user_via_user if current_user.update(user_params) flash.notice = "Your profile was sent for moderation. We will moderate it asap!" else flash.alert = "Something went wrong! Please try again." end redirect_to root_path end Some other references: (my question at the end) schema.rb: languages table: create_table "languages", force: true do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" t.integer "user_id" end users table: t.string "languages" language.rb model: class Language < ActiveRecord::Base belongs_to :user end and user.rb model: class User < ActiveRecord::Base has_many :languages end The view: <%= f.label :languages %> <%= f.select :languages, Language.all.map{ |l| [l.name, "#{l.id}"] }, {}, { :multiple => true } %> I am not sure why "languages" is not permitted and also if my concept of code is correct |
Sort by date in descending order in ruby in rails Posted: 18 Mar 2016 04:40 AM PDT I would like to sort my list in a descending order by date which as a "New user list", in the database I have a column which is t.datetime "created_at", null: false This is the time when a new user registered, in the view, I have the code like this: %table.table.table-striped.table-hover %thead %h3 New Users %hr %th Name %th Company %th Role %th Created date %th{:width => '50'} %th{:width => '50'} %th{:width => '50'} %tbody - @users.each do |user| -if user.role == "trial-member" - @created_at.sort{|a,b| b.created_at <=> a.created_at}.each do |created_at| %tr %td = user.first_name = user.last_name %td= user.company %td= user.role %td= user.created_at %td= link_to 'Approve', edit_user_path(user), {:class => 'btn btn-success btn-sm'} but this gives an error that "undefined method `sort' for nil:NilClass", what shall I do to sort the list in table descending by created date? Thank you. |
Heroku and ClearDB error Posted: 18 Mar 2016 06:37 AM PDT I have a Ruby on Rails application with a mysql database (using the gem mysql2). Since Heroku runs postgres I followed this step in order to make it work: $>heroku addons:create cleardb:ignite $>heroku config | grep CLEARDB_DATABASE_URL $>heroku config:set DATABASE_URL='mysql2://my-url' As described here. The problem is that I get this error on the last command: Setting config vars and restarting xxxxxx-xxxxx-16407... !!! ▸ Cannot overwrite attachment values DATABASE_URL. And my application can't run: 2016-03-18T10:31:31.413121+00:00 heroku[run.1567]: State changed from up to complete 2016-03-18T10:31:34.818303+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=xxxxx-xxxxx-16407.herokuapp.com request_id=236455b8-7a02-49f0-8e2e-a67341a81580 fwd="151.225.234.109" dyno= connect= service= status=503 bytes= 2016-03-18T10:31:35.308136+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=xxxxx-xxxx-16407.herokuapp.com request_id=974dab02-e914-42fb-ad96-5476e30e9d17 fwd="151.225.234.109" dyno= connect= service= status=503 bytes= 2016-03-18T10:31:35.434538+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=xxxx-xxxxx-16407.herokuapp.com request_id=22bfdfd8-9cdf-4e3d-bb13-c616591bd91f fwd="151.225.234.109" dyno= connect= service= status=503 bytes= I have already execute bundle install and rake db:migrate on the heroku machine. Do you know how can I solve the issue? |
DRY Rails controller to avoid repeating multiple times same method Posted: 18 Mar 2016 04:14 AM PDT I would like to DRY my controller as I use some snippets/blocks of code many times inside the same controller (I have removed some as it was too long but this already gives an idea of the repetition). Here are the blocks I keep repeating : @deal = search_deal
@next_deal = find_next_deal
@userdeal = find_or_create_userdeal_participation
@user_credits = calculate_user_credits_in_deal
I'm quite rookie and don't know how to do this but I feel this code should be factorized. class DealsController < ApplicationController before_filter :find_deal, :only => [ :showcase ] before_filter :ensure_canonical_deal_path!, :only => [ :showcase ] def showcase # find appropriate deal @deal = search_deal respond_to do |format| format.html # showcase.html.erb format.json { render json: @deal } end end def buy_stuff @deal = search_deal # bring 'next deal' url to the view @next_deal = find_next_deal # USER IS SIGNED-IN if user_signed_in? @userdeal = find_or_create_userdeal_participation @user_credits = calculate_user_credits_in_deal # if: user still has credits available if @user_credits >= 1 #do this respond_to do |format| format.js end else respond_to do |format| # do that end end # USER IS NOT SIGNED-IN else respond_to do |format| format.js { render :template => "deals/call_to_sign_in.js.erb" } end end end def show_discounts @deal = search_deal respond_to do |format| #do that end end def pending_deals @deal = search_deal # bring 'next deal' url to the view @next_deal = find_next_deal if user_signed_in? @userdeal = find_or_create_userdeal_participation @user_credits = calculate_user_credits_in_deal end respond_to do |format| #do this end end def ask_question @deal = search_deal respond_to do |format| #do that end end protected def ensure_canonical_deal_path! if request.path != actual_deal_page_path(@deal) redirect_to actual_deal_page_path(@deal, :format => params[:format]), :status => :moved_permanently return false end end private # DRY file as this is used multiple times # trick source - http://blog.rstankov.com/rails-anti-pattern-setting-view-variables-in-before-actions/ def search_deal Deal.friendly.find(params[:id]) end def find_or_create_userdeal_participation UserDeal.where('user_id = ? AND deal_id = ?', current_user.id, @deal.id).take || UserDeal.create(user_id: current_user.id, deal_id: @deal.id) end def calculate_user_credits_in_deal current_user.credit_nb + @userdeal.history end def find_next_deal Deal.order_next_deal_at(@deal).next end end |
Multiple Check Boxes in form to return Array, but returning 0 in Rails Posted: 18 Mar 2016 03:27 AM PDT I have a form and i am trying to submit a list of languages spoken via check boxes, that will be submitted as an Array, serialised in the controler and saved to DB. According to the docs, I should be able to use <%= f.check_box :languages, {multiple: true}, "EN", nil %> <%= f.check_box :languages, {multiple: true}, "ES", nil %> <%= f.check_box :languages, {multiple: true}, "US", nil %> Which gives the HTML <input type="checkbox" value="EN" name="service[languages][]" id="service_languages_en"> <input type="checkbox" value="ES" name="service[languages][]" id="service_languages_es"> <input type="checkbox" value="US" name="service[languages][]" id="service_languages_us"> in controller params.require(:service).permit(..., :languages => []) But in my logs all i get from the params is "languages"=>"0", Im sure its something obvious im missing, so any help would be massively appreciated! I know it could (and probably should) be done with has_many association, but I have reasons for wanting to do it this way for now. Thanks in Advance |
Two devise models, two application controllers, one controller Posted: 18 Mar 2016 05:23 AM PDT So I am running into a problem where I have two separate devise models (Admin and User), and because I am using a multi tenancy gem called Milia I need to two application controllers (One for the Admin which is outside of the tenancy and one for the User which is inside the tenancy. The problem is I need to access one controller from both of those devise models, but I can only inherit that controller from one of the below application controllers. Is there a way around this where I can specify which user should use which application controller when hitting the controller for a particular resource? Or is there another way around this problem? The two application controllers look like this class AdminApplicationController < ActionController::Base before_action :authenticate_admin! end class ApplicationController < ActionController::Base before_action :authenticate_tenant! end |
Rails 4 - Grouping ActiveRecord items based on associated models Posted: 18 Mar 2016 03:52 AM PDT I have a Rails 4 app, where I am making a table that shows me what items I have in stock. Items that are not in stock are NOT displayed. In my controller I do the following: @stock = Stock.all And In my view I have this: <table> <% @stock.each do |item| %> <tr> <td><%= item.id %></td> <td><%= item.product.id %></td> <td><%= item.product.description %></td> </tr> <% end %> </table> This is the outcome: +---------------------------------------------+ | Stock ID | Product ID | Product description | +---------------------------------------------+ | 1 | 63 | A cool wheel | +---------------------------------------------+ | 2 | 63 | A cool wheel | +---------------------------------------------+ | 3 | 63 | A cool wheel | +---------------------------------------------+ | 4 | 26 | A red coat | +---------------------------------------------+ | 5 | 26 | A red coat | +---------------------------------------------+ | 6 | 99 | Something | +---------------------------------------------+ | ... | ... | ... | But I would like to have it grouped by amount. How could I achieve that? This is what I would like to get +---------------------------------------------+ | Amount | Product ID | Product description | +---------------------------------------------+ | 3 | 63 | A cool wheel | +---------------------------------------------+ | 2 | 26 | A red coat | +---------------------------------------------+ | 1 | 99 | Something | +---------------------------------------------+ | ... | ... | ... | I thought this would do it, but it did not work: .count(:all, group: "product_id") |
Ruby On Rails form error message Posted: 18 Mar 2016 04:01 AM PDT I'm making a form in my web app, that has to be filled, else I want to display an error message on the page. I followed some tutorials, but I'm encountering an issue : when I submit this form, the app is returning on the previous page without displaying the error message because the form is empty. Here is my html.erb : <%= form_for @task do |f| %> <%= render 'shared/add_task_error_messages' %> <%= f.text_field :title, :class => "col-lg-4 col-lg-offset-4 field", :placeholder => "Title", :maxlength => "80" %></br> <%= f.text_field :department, :class => "col-lg-4 col-lg-offset-4 field", :placeholder => "Department", :maxlength => "80" %></br> <%= f.text_field :startDate, :class => "col-lg-4 col-lg-offset-4 datepicker", :placeholder => "Start date", :maxlength => "80" %></br> <%= f.text_field :endDate, :class => "col-lg-4 col-lg-offset-4 datepicker", :placeholder => "End date", :maxlength => "80" %></br> <%= f.submit :Submit, :value => "Create", :class => "col-lg-2 col-lg-offset-5", :id => "create_task" %> <% end %> my controller methods : def create @task = Task.new(task_params) if @task.save redirect_to @task else render 'new' end end private def task_params params.require(:task).permit(:title, :department, :startDate, :endDate) end and the '_add_task_error_messages.html.erb' file with the error message : <% if @task.errors.any? %> <div id="error_explanation"> <div class="alert alert-danger"> The form contains <%= pluralize(@task.errors.count, "error") %>. </div> <ul> <% @task.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %> and the model : class Task < ActiveRecord::Base validates :title, :presence => true validates :department, :presence => true validates :startDate, :presence => true validates :endDate, :presence => true # Returns tasks array of the project def self.getProjectTasks projectTasks = Array.new result = Task.where("identifier = ?", 1) (1..result.length).each do |i| task = Array.new task.push(result.find(i).title) task.push(result.find(i).department) task.push(result.find(i).content) task.push(result.find(i).duration) task.push(result.find(i).startDate) task.push(result.find(i).endDate) projectTasks.push(task) end return projectTasks end end UPDATE : In fact, I'm getting an error when the app is returning on the 'new' page when the form is submitted, without showing the error message. When it go on this 'new' page, I'm getting an error on the html.erb because I have an object which has to be initialized. Here is the 'new' page : <div class="tasks"> <% @projectTasks.each do |task| %> # The error is here, "undefined method `each' for nil:NilClass" <div class="task col-lg-8"> <div class="details"> <div class="detail"><%= task[0] %></div> <div class="detail"><%= task[1] %></div> <div class="detail"><%= task[3] %> days</div> <div class="detail"><%= task[4] %> - <%= task[5] %></div> </div> </div> <% end %> </div> but this error is only showing when the app is redirecting after the submitted form, and I don't want it to display the 'new' page, I only want to stay on my form with the error message of the empty form. |
I can't make my pic appear on website Posted: 18 Mar 2016 02:57 AM PDT I am trying make "home-bg.jpg" appear on website but it doesn't appear. posted my codes below. need your help. <header class="intro-header" style="<%= asset_path "home-bg.jpg" %>"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <div class="site-heading"> <h1>Clean Blog</h1> <hr class="small"> <span class="subheading">A Clean Blog Theme by Start Bootstrap</span> </div> </div> </div> </div> </header> |
ruby gem not install [duplicate] Posted: 18 Mar 2016 02:47 AM PDT This question already has an answer here: I have a fedora linux and latest version of ruby and ruby-gems. But when i try gem install "every gems"(rails,bcrypt,nokogiri,...) : gem install rails Building native extensions. This could take a while... ERROR: Error installing rails: ERROR: Failed to build gem native extension. /usr/bin/ruby -r ./siteconf20160318-17953-m5t2el.rb extconf.rb checking if the C compiler accepts ... *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib64 --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/usr/bin/$(RUBY_BASE_NAME) --help --clean /usr/share/ruby/mkmf.rb:456:in `try_do': The compiler failed to generate an executable file. (RuntimeError) You have to install development tools first. from /usr/share/ruby/mkmf.rb:571:in `block in try_compile' from /usr/share/ruby/mkmf.rb:522:in `with_werror' from /usr/share/ruby/mkmf.rb:571:in `try_compile' from extconf.rb:80:in `nokogiri_try_compile' from extconf.rb:87:in `block in add_cflags' from /usr/share/ruby/mkmf.rb:619:in `with_cflags' from extconf.rb:86:in `add_cflags' from extconf.rb:336:in `<main>' extconf failed, exit code 1 Gem files will remain installed in /home/ice-fox/.gem/ruby/gems/nokogiri-1.6.7.2 for inspection. Results logged to /home/ice-fox/.gem/ruby/extensions/x86_64-linux/nokogiri-1.6.7.2/gem_make.out I installed ruby developer kit . I tried install gems with gem install and bundle from git source. But i still cant install gems. How i can install these gems. |
Error with browserify-rails Posted: 18 Mar 2016 02:36 AM PDT This was working great using rails 4.2.4 but not Im using 4.2.5 with ruby 2.2.3. Other project works ok but not with this one. Error while running /Users/sylar/Sites/rails/devstart/node_modules/.bin/browserifyinc --transform reactify --extension=".jsx" --list --cachefile=/Users/sylar/Sites/rails/devstart/tmp/cache/browserify-rails/browserifyinc-cache.json -o "/Users/sylar/Sites/rails/devstart/tmp/cache/browserify-rails/output20160318-74935-1daiy59" - : /Users/sylar/Sites/rails/devstart/node_modules/module-deps/index.js:269 params.basedir = pkg.__dirname; ^ TypeError: Cannot read property '__dirname' of undefined at nr (/Users/sylar/Sites/rails/devstart/node_modules/module-deps/index.js:269:37) Want to use npm in my rails app and with react. I use react rails and browserify-rails. I use this way to get my other working project to work. For the life of me, I cant get this error to go. It has been a long time so Im not sure what I did to get this to work. |
Rails: How to listen to / pull from service or queue? Posted: 18 Mar 2016 04:52 AM PDT Most Rails applications work in a way that they are waiting for requests comming from a client and then do their magic. But if I want to use a Rails application as part of a microservice architecture (for example) with some asychonious communication (Serivce A sends an event into a Kafka or RabbitMQ queue and Service B - my Rails app - is supposed to listen to this queue), how can I tune/start the Rails app to immediately listen to a queue and being triggered by event from there? (Meaning the initial trigger is not comming from a client, but from the App itself.) Thanks for your advice! |
embedded ruby code doesn't execute when I insert .txt file into div (Rails + jQuery) Posted: 18 Mar 2016 02:31 AM PDT I am loading .txt files into a div in my file.html.erb. This works fine but when I embed ruby code like this <% Code %> in the .txt file that I am loading in it is just being displayed as text instead of executing it. The other ruby code in the actual file.html.erb works normally so I figured I have to add something to my .txt file that I am loading in using JQuery .load? |
Device, do not send emails confirmation Posted: 18 Mar 2016 03:00 AM PDT When a user sign up or reconfirm, email is not sent. I can not understand where the error, what do I look for? How me check? Please, help, thank you. Auth.rb module Models::User::Auth extend ActiveSupport::Concern included do # acts_as_authentic do |c| # c.validates_length_of_login_field_options :in => 1..50 # c.validates_format_of_login_field_options :with => /\A[[[:alnum:]]\.+\-_\p{S}@\u2020]([[[:alnum:]]\.+\-_\p{S}@ ]+)?[[[:alnum:]]\.+\-_\p{S}@\u2020]?$/u # end attr_accessor :login attr_accessor :terms validates :terms, acceptance: true, if: Proc.new { |user| user.new_record? } attr_accessor :current_password # attr_accessor :reset_password # validate :validate_current_password, if: :changes_password? # validates :email, format: /\A(\S+)@([a-z0-9-]+)(\.)([a-z]{2,4})(\.?)([a-z]{0,4})+\z/ attr_accessible :username, :email, :login, :password, :password_confirmation, :remember_me, :terms, :current_password, :reset_password devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :token_authenticatable, :async, :encryptable, :confirmable #, :omniauthable scope :confirmed, where(:confirmed_at.not_eq => nil) scope :unconfirmed, where(confirmed_at: nil) end def unconfirmed? confirmed_at == nil end def not_deleted? deleted_at.nil? end def active_for_authentication? # Uncomment the below debug statement to view the properties of the returned self model values. # logger.debug self.to_yaml super && not_deleted? end def inactive_message not_deleted? ? super : :special_condition_is_not_valid end # module ClassMethods # def find_first_by_auth_conditions(warden_conditions) # conditions = warden_conditions.dup # if login = conditions.delete(:login) # where(conditions). # where('lower(username) = :v OR lower(email) = :v', v: login.downcase).first # else # where(conditions).first # end # end # end protected def changes_password? not new_record? and password.present? #and not reset_password end def validate_current_password errors.add(:current_password, :invalid) unless valid_password?(current_password) end end development.rb config.action_mailer.delivery_method = :letter_opener config.action_mailer.smtp_settings = { :address => "127.0.0.1", :port => 1025 } config.action_mailer.default_url_options = { :host => 'localhost:3666' } config.action_mailer.raise_delivery_errors = true config.action_mailer.perform_deliveries = true controllers/confirmations_controller.rb class ConfirmationsController < Devise::ConfirmationsController def new super resource.login = current_user.email if user_signed_in? end protected def after_resending_confirmation_instructions_path_for(resource_name) if user_signed_in? home_path else new_session_path(resource_name) end if is_navigational_format? end # The path used after confirmation. def after_confirmation_path_for(resource_name, resource) '/profile' end end |
Preferred way of handling actions in a rest api Posted: 18 Mar 2016 03:06 AM PDT While working on my REST api, i was wondering what's the best practice is, when you need to handle certain actions, let me explain with a example. Say i got the following model. create_table "requests", force: :cascade do |t| t.datetime "start_date" t.float "price" t.string "status", default: 'open' t.datetime "created_at", null: false t.datetime "updated_at", null: false end I would then have the usual CRUD paths/actions (show, create, update, destroy) for that model. Alright, say that i want to change the status of a given request record to 'accepted', i will sent my updated attributes to the update path, and wola. But what if i wanted to react to certain status update, i might want to send mail to the involved users when the request updates. I could create an entire new action for that behavior. /api/v1/request/:id/approve Then i could send my mail and update the status of the request in my action. However i can't help but feel that i should be using the update function, as what i'm really doing is just updating the request status, the mail is more of a "side effect". Then i had a look at How to detect attribute changes from model? which instead would let me pass the functionality to the model instead, sending a mail if the status changes before saving it. However this will cause a lot of before actions, which i don't find particular pretty either. What do you recommend? |
Rails 5 API only cannot render 404.html Posted: 18 Mar 2016 04:44 AM PDT I created a Rails 5 API only project. Just for testing Rails to make sure I can render a page should I choose to, I have the following code: def show render file: "#{Rails.root}/public/404.html", layout: false, status: 404 end But I'm not seeing any 404 html page. All I'm seeing is a blank white page. Inspecting the HTML elements does show any relevant HTML tags. I get the 404 HTTP Status in my Chrome browser. The route works. Is it because my project was generated using the --api flag that is preventing any HTML page to be rendered at all? Edit I've also looked at these Stackoverflow posts: Rails not rendering 404 in production render a 404 page on routing error in rails I have set: # Show full error reports. config.consider_all_requests_local = false In my config/environments/development.rb and also restarted the local server. Extra Edit Extra info in case it helps. I have routes: get '/cats', to: 'cats#index' get '/cats/:id', to: 'cats#show' Update Generated a new project using Rails 5 but without the --api flag. Everything seems to work, so my speculation right now is something to do with the --api not allowing any view template or html file to be rendered at all. What is baffling to me is why going to localhost:3000 shows a pretty "Yay, you're on Rails!" default page... What is that suppose to mean, that when you generate a Rails project with the --api that you cannot have any views at all ? I thought it was more of a slim/lean starting point and lets the developer add further things like view to the API if needed. Maybe the assets needs to be compiled somehow, but 404.html is in the public folder. |
Use React Router or classic multi page to create Dashboard Posted: 18 Mar 2016 02:01 AM PDT In the long run, what way will be easier to maintain and develop? In my mind, because dashboard app will have A LOT of javascript, so why not just use React and React Router with it? But I have very bad experience with keeping states in UI using javascript to be consistent, all the callbacks killing me :(. So, if you need to build dashboard app now, which one will you use, and why? Thank you. NOTE: the backend will use Rails. |
Handle HTML and JS request based on javascripts on/off in rails Posted: 18 Mar 2016 02:19 AM PDT When user turn off JavaScript then follow HTML request flow otherwise follow JS request flow. HTML flow means : request as html => render html template => response as HTML ( when JavaScript off in browser ) JS flow means : request as JS => render JS template => response as JS ( when JavaScript on in browser ) I have one solution for that and that is :- I have to write code to handle both request in my all controller something like this : respond_to do |format| format.html format.js end
I have to create both type of template js and html and render common data in it. But in above solution, i think there is very much duplicate code like we have to write respond_to code in every controller and we have to create two copy of every page (js.html, erb.html). So i need standard solution(if any) to handle both kind of request based on JavaScript enabled/disable in browser without any duplication. |
No comments:
Post a Comment