Rails user login is nil Posted: 31 Oct 2016 07:39 AM PDT I have my rails app and when I try to login (I have created user called "test") I see this in the console: Parameters: {"utf8"=>"✓", "authenticity_token"=>"tlKwtMBNJ4LzJuJq13bUscAGpumdr+HVmUlGlfIudT9032DMXNxqa0d2VCxCvDZRDe1D6pFfaTafSRiL6tUvhw==", "session"=>{"login"=>"", "password"=>"[FILTERED]"}, "commit"=>"Log in"} User Load (1.7ms) SELECT `users`.* FROM `users` WHERE `users`.`login` IS NULL LIMIT 1 I see that in the session parameters application can't get user login (and maybe password too). Below are my user and session controllers: class UsersController < ApplicationController before_action :require_admin def new @users = User.new end def create @user = User.new(user_params) if @user.save session[:user_id] = @user.id current_user = @user.id redirect_to @user else redirect_to '/login' end end private def user_params params.require(:user).permit(:first_name, :last_name, :email, :login) end end Session controller: class SessionsController < ApplicationController def new end def create @user = User.find_by_login(params[:login]) if @user && @user.authenticate(params[:password]) session[:user_id] = @user.id redirect_to '/' else flash[:error] = 'err' redirect_to '/login' end end def destroy session[:user_id] = nil redirect_to root_url end end I have also tested the user creation and the record is in the database. |
Get attribute values at beginning and end of a date range Posted: 31 Oct 2016 07:45 AM PDT I have a database table stockmovements with columns DATE, PRODUCT, UNITS,TYPE, STOCK. STOCK saves the value of stock at that date when a certain stock movement was done. TYPE can be purchase or sold or return. I group by product so that any row of the table in my view shows a product. Then I want to create 2 columns. Stock start and stock end. Showing stock values at the first and last date of a date range. So that later let say I apply I filter 1st october - 31st october the 2 columns will show stock value at 1st october and stock value at 31st october. If no filters are applied columns will show stock value of earliest and latest stockmovement among all values in database. And in the middle columns to show units for each stockmovement type. So that in the end will be product, stock start, purchased, sold, returned, stock end. This is just to give an idea about the general logic but it doesn't really matter for the question. I have this in my controller: @stockmovements = Stockmovement.all.group(:PRODUCT) What should I add to my view: <td><%= number_to_human stockmovement.STOCK, precision: 0 %></td> to get the stock values at beginning and end of the date range? Or should this be done in the model? I basically need STOCK where DATE= start date and STOCK where DATE= end date. But I can't find any helper to do that. |
rolify (n+1) issue using with_role Posted: 31 Oct 2016 07:17 AM PDT facing issue of n+1 problem my controller code def index @merchants = Merchant.includes(users: [:users_roles]) .page(params[:page]).per(10) end on view @merchants.each do |m| admins = m.users.with_role('merchant') it is fetching 10 queries while listing |
Edit comment , nested form through Zurb Reveal - Rails Posted: 31 Oct 2016 07:08 AM PDT First of all this is the error First argument in form cannot contain nil or be empty What I have is a Thread model and controller and a Answer model and Controller. And what I am trying to do is edit the answer on the show page of the thread via a zurb Reveal Modal. and this what my code looks like Thread Modal class Thread < ApplicationRecord belongs_to :user has_many :answers extend FriendlyId friendly_id :subject, use: :slugged end Answer Model class Answer < ApplicationRecord belongs_to :user belongs_to :thread end Answer Controller def edit @thread = Thread.friendly.find(params[:thread_id]) @answer = @thread.answers.find(params[:id]) render :layout => false end def update @thread = Thread.friendly.find(params[:thread_id]) @answer = @thread.answers.find(params[:id]) respond_to do |format| if @answer.update(params[:answer].permit(:content)) format.html { redirect_to thread_path(@thread) } format.json { render :show, status: :ok, location: @answer } else format.html { redirect_to @thread, alert: "Unable to save your post" } format.json { render json: @answer.errors, status: :unprocessable_entity } end end end Show Thread <%= render @thread.answers %> Answer Partial <% if current_user.present? && current_user.id == answer.user_id %> <ul class="edit-links pull-right"> <li> <%= link_to 'Edit', edit_thread_answer_path(answer.thread, answer), :remote => true, class: "edit", "data-open" => "editModal", "data-open-ajax" => edit_thread_answer_path(answer.thread, answer) %> </li> <li> <%= link_to 'Destroy', [answer.thread, answer], method: :delete, data: { confirm: 'Are you sure?' }, class: "destroy" %> </li> </ul> <% end %> <p> <%= simple_format answer.content %> </p> <div id="editModal" class="reveal" data-reveal> <%= render :partial => 'answers/edit_form' %> <button class="close-button" data-close aria-label="Close modal" type="button"> <span aria-hidden="true">×</span> </button> </div> Answer Edit Form Partial <h1>Edit Answer</h1> <%= form_for([@thread, @answer]) do |f| %> <%= f.text_area :content, :rows => "10" %> <%= f.submit "Update", :class => "button add-thread" %> <% end %> I get the error when I try to open a thread#show its says the error is here ArgumentError in Threads#show <%= form_for([@thread, @answer]) do |f| %> Trace of template inclusion: app/views/answers/_answer.html.erb, app/views/threads/show.html.erb Any suggestions ? where may the error be ? |
How to create delayed complex objects creation Posted: 31 Oct 2016 07:38 AM PDT I got this problem: I have a complex model, Recipe, which have_many Ingredients, belongs_to User, have paperclips images. I attempt to create some base objects for each new User. For example: a recipe, with it's ingredients (which are differents for each User). How to create a job to handle these recipes creations? knowing that they must be editable by their users, etc. It's easy for a basic model with no relationships but I'm blocked here... -I don't want to create Ingredients or Recipe for all users, I want them to be able to delete them. Here are the params for a single recipe creation by a random user : Parameters: {"utf8"=>"✓", "recipe"=>{"name"=>"Recipe test", "category"=>"Chocolate", "owner"=>"Tom", "baking"=>"100", "note"=>"", "quantities_attributes"=>{"0"=>{"ingredient_id"=>"6434", "weight"=>"100", "_destroy"=>"false"}, "1"=>{"ingredient_id"=>"6681", "weight"=>"10", "_destroy"=>"false"}, "2"=>{"ingredient_id"=>"6668", "weight"=>"210", "_destroy"=>"false"}, "3"=>{"ingredient_id"=>"6591", "weight"=>"100", "_destroy"=>"false"}, "4"=>{"ingredient_id"=>"6611", "weight"=>"20", "_destroy"=>"false"}, "5"=>{"ingredient_id"=>"", "weight"=>"", "_destroy"=>"false"}}, "process"=>"<p>This is a f*** test of recipe recipe creation</p>\r\n\r\n<p><img alt=\"\" height=\"26\" src=\"http://localhost:3000/assets/ckeditor/plugins/smiley/images/Emoji Smiley-109.png\" title=\"\" width=\"26\" /></p>\r\n"}, "commit"=>"SUBMIT"} Any idea ? |
Rails assosiations routing Posted: 31 Oct 2016 07:04 AM PDT I have two models Blog and User with following association Blog belongs_to :user My routes are as follows resources :users, shallow: true do resources :blogs end These are the routes generated user_blogs GET /users/:user_id/blogs(.:format) blogs#index POST /users/:user_id/blogs(.:format) blogs#create new_user_blog GET /users/:user_id/blogs/new(.:format) blogs#new edit_blog GET /blogs/:id/edit(.:format) blogs#edit blog GET /blogs/:id(.:format) blogs#show The question is why some routes ( new_user_blog for example) has the right routing, but others (edit_blog should be edit_user_blog ) are wrong? |
Rails 5 - Cannot initialize ActionCable Posted: 31 Oct 2016 06:33 AM PDT I just upgraded my app to Rails 5, I'm following a tutorial about ActionCable basics, but I cannot start a server. Everytime I try to do so, I get the following error: uninitialized constant ActionCable (NameError) It seems like it comes from my routes.rb file, from this line : mount ActionCable.server => '/cable' This line is specified in every tutorial I've read so far, so I assume it is required for Actioncable to work. Has anyone encountered this problem before ? My gemfile is up-to-date, i'm using rails 5.0.0.1 |
Rails: Still confused about SQL Injection Posted: 31 Oct 2016 06:12 AM PDT I've made some posts about translating user input from a search box into an ActiveRecord Parameterized statement, which may be vulnerable to SQL injection, but I think I may have a solution. Here's how the search works. The user enters something like this into the search box: name="hello" AND NOT address.town="Villa" Internally, I convert it to: query = ["name LIKE ? AND address.town NOT LIKE ?", "hello", "villa"] for: if search query = convert_search_to_query search begin includes(:address).where(query) # rescue Exception ... ... ... Here's my idea: simply check the user-inputted attributes ("name", "address.town" in this case) to make sure it's an exact match for the acceptable list of user attributes. If I were to do this, I think that there would be no SQL Injection possible since I am using parameterized statements (with the '?') to handle the only part of the user's input I can't check -- the values he entered for each attribute. Based on what I read from other posts on here, I don't see how this code could be any more vulnerable than a normal parameterized search, but I don't have a lot of experience with SQL injection. Is it vulnerable? Also: I understand that there are plugins that may be able to help, but what I want to do is really very simple, and is already working, and I'd rather keep my app as lightweight as possible. |
Google Adsense, CORS and Rails in Safari dumps thousands of console errors Posted: 31 Oct 2016 06:23 AM PDT I am serving google ads on a ssl site successfully, with CORS headers set properly (and wide open) by rack-cors as: Rails.configuration.middleware.insert_before 0, Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: :any end end I can confirm that the headers are there with a curl call: $ curl -I https://viewing.nyc -H "Origin: https://foobar.com" ... Access-Control-Allow-Origin: https://foobar.com Access-Control-Allow-Methods: GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS Access-Control-Max-Age: 1728000 ... If you visit in Chrome or Firefox, there are no cross site scripting errors in the console, yet on Safari, there are thousands. Blocked a frame with origin "https://googleads.g.doubleclick.net" from accessing a frame with origin "https://viewing.nyc". Protocols, domains, and ports must match. Live example I've poured through the rack-cors issues page with no solution working thus far. Why is this happening only on Safari, and how can I fix it? |
Rails foreign key confusion Posted: 31 Oct 2016 06:20 AM PDT I'm trying to learn rails. I have 2 tables Users and Posts, I want to link the email address from Users to Posts but I'm not sure how to go about it. I have pre-made the table but how to I go about adding a Users.email to the new select box, so far I have this in the index.html.erb. <tbody> <% @posts.each do |post| %> <tr> <td><%= post.title %></td> <td><%= post.time %></td> <td><%= post.body %></td> <td><%= post.user_id %></td> <td><%= link_to 'Show', post %></td> <td><%= link_to 'Edit', edit_post_path(post) %></td> <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %> And this in my form.html.erb %= form_for(post) do |f| %> <% if post.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2> <ul> <% post.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :title %> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :time %> <%= f.datetime_select :time %> </div> <div class="field"> <%= f.label :body %> <%= f.text_area :body %> </div> <div class="field"> <%= f.label :user_id %> <%= f.number_field :user_id %> </div> <div class="actions"> <%= f.submit %> </div> <% end %> As you can see I have a user_id field but how would I go about linking that to the primary key of Users? and then to do and email lookup? Thanks. |
A field should not be present if according to an enum Posted: 31 Oct 2016 07:06 AM PDT I have an enum status: enum status: [ :x, :y , :z ] Each status has model attributes that only relate to the selected status. How would I validate that if the status is 'x' that the attributes related to 'y' and 'z' are blank? And simiar validations are needed for status 'y' and status 'z'. I want to validate that only the fields (attributes) that relate to the selected status are present. |
Multidomain Routing, with same routing names Posted: 31 Oct 2016 05:29 AM PDT constraints DomainRouting.new("other.local") do devise_for :users, controllers: { registrations: "registrations" } get "/*permalink", to: "mods#show", as: :mod, constraints: ModConstraint.new(:other) root to: "categories#index" end constraints DomainRouting.new("something.local") do scope "something" do devise_for :users, controllers: { registrations: "registrations" } get "/*permalink", to: "mods#show", as: :mod, constraints: ModConstraint.new(:something) root to: "categories#index" end end how can i achieve the following scenario? ArgumentError: Invalid route name, already in use: 'new_user_session' (same goes for mods_path ) we need other.local/:permalink and something.local/something/:permalink (and +8 other domains, with different routings (but same controllers)) |
Rails + Materialize + turbolinks takes longer time for asset precompile Posted: 31 Oct 2016 05:34 AM PDT I'm using Rails 4.2 and materialize-sass gem for materialized UI. In the production environment, it takes nearly 10min for asset precompiling. Is there any way to reduce the time. I have used turbolinks in my application. I have disabled turbolinks based on controller as, In application_helper.rb def get_access_to_turbolinks controllers = ["home", "pages"] if controllers.include? params[:controller] return "data-turbolinks='true'" else return "data-turbolinks='false'" end end In application.html.erb <body <%= get_access_to_turbolinks.html_safe %>"> Data-turbolinks becomes false in the HTML code and even then the page is not loading as normal, instead it is rendering. Also I have provided some initializer for select, dropdown inside the function called $.fn.initialise_me(). This function has been called inside the following, $(document).ready(function(){ $.fn.initialise_me(); }); document.addEventListener("turbolinks:load", function() { $.fn.initialise_me(); }); |
NoMethodError though method has been defined Posted: 31 Oct 2016 05:28 AM PDT I have a Ruby On Rails weblog application and am getting a NoMethodError in PostsController#show issue when opening a post. PostsController is stored under rails/weblog/app/controllers I get undefined method 'set_current_page' for #<PostsController:0x007fb162831e70> however set_current_page is defined like so: private def set_current_page @current_page = params[:page] || 1 end end and then used in a before_action before_action :set_current_page, except: [:index] before_action :set_post, only: [:show, :edit, :update, :destroy] Full stack trace: activesupport (5.0.0.1) lib/active_support/callbacks.rb:382:in `block in make_lambda' activesupport (5.0.0.1) lib/active_support/callbacks.rb:150:in `block (2 levels) in halting_and_conditional' actionpack (5.0.0.1) lib/abstract_controller/callbacks.rb:12:in `block (2 levels) in <module:Callbacks>' activesupport (5.0.0.1) lib/active_support/callbacks.rb:151:in `block in halting_and_conditional' activesupport (5.0.0.1) lib/active_support/callbacks.rb:454:in `block in call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:454:in `each' activesupport (5.0.0.1) lib/active_support/callbacks.rb:454:in `call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:101:in `__run_callbacks__' activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_process_action_callbacks' activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks' actionpack (5.0.0.1) lib/abstract_controller/callbacks.rb:19:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/rescue.rb:20:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `block in instrument' activesupport (5.0.0.1) lib/active_support/notifications/instrumenter.rb:21:in `instrument' activesupport (5.0.0.1) lib/active_support/notifications.rb:164:in `instrument' actionpack (5.0.0.1) lib/action_controller/metal/instrumentation.rb:30:in `process_action' actionpack (5.0.0.1) lib/action_controller/metal/params_wrapper.rb:248:in `process_action' activerecord (5.0.0.1) lib/active_record/railties/controller_runtime.rb:18:in `process_action' actionpack (5.0.0.1) lib/abstract_controller/base.rb:126:in `process' actionview (5.0.0.1) lib/action_view/rendering.rb:30:in `process' actionpack (5.0.0.1) lib/action_controller/metal.rb:190:in `dispatch' actionpack (5.0.0.1) lib/action_controller/metal.rb:262:in `dispatch' actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:50:in `dispatch' actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:32:in `serve' actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:39:in `block in serve' actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `each' actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `serve' actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:725:in `call' rack (2.0.1) lib/rack/etag.rb:25:in `call' rack (2.0.1) lib/rack/conditional_get.rb:25:in `call' rack (2.0.1) lib/rack/head.rb:12:in `call' rack (2.0.1) lib/rack/session/abstract/id.rb:222:in `context' rack (2.0.1) lib/rack/session/abstract/id.rb:216:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/cookies.rb:613:in `call' activerecord (5.0.0.1) lib/active_record/migration.rb:552:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call' activesupport (5.0.0.1) lib/active_support/callbacks.rb:97:in `__run_callbacks__' activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_call_callbacks' activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks' actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:36:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/remote_ip.rb:79:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call' web-console (3.4.0) lib/web_console/middleware.rb:135:in `call_app' web-console (3.4.0) lib/web_console/middleware.rb:28:in `block in call' web-console (3.4.0) lib/web_console/middleware.rb:18:in `catch' web-console (3.4.0) lib/web_console/middleware.rb:18:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call' railties (5.0.0.1) lib/rails/rack/logger.rb:36:in `call_app' railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `block in call' activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `block in tagged' activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:26:in `tagged' activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `tagged' railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `call' sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call' rack (2.0.1) lib/rack/method_override.rb:22:in `call' rack (2.0.1) lib/rack/runtime.rb:22:in `call' activesupport (5.0.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call' actionpack (5.0.0.1) lib/action_dispatch/middleware/static.rb:136:in `call' rack (2.0.1) lib/rack/sendfile.rb:111:in `call' railties (5.0.0.1) lib/rails/engine.rb:522:in `call' puma (3.6.0) lib/puma/configuration.rb:225:in `call' puma (3.6.0) lib/puma/server.rb:578:in `handle_request' puma (3.6.0) lib/puma/server.rb:415:in `process_client' puma (3.6.0) lib/puma/server.rb:275:in `block in run' puma (3.6.0) lib/puma/thread_pool.rb:116:in `block in spawn_thread' The posts_controller.rb file: class PostsController < ApplicationController before_action :set_current_page, except: [:index] before_action :set_post, only: [:show, :edit, :update, :destroy] # GET /posts # GET /posts.json def index @posts = Post.paginate(page: params[:page], per_page: params[:per_page]) .order('title, user_id') end # GET /posts/1 # GET /posts/1.json def show end # GET /posts/new def new @post = Post.new end # GET /posts/1/edit def edit end # POST /posts # POST /posts.json def create @post = Post.new(post_params) @post.user = User.find_by email: params[:email] respond_to do |format| if @post.save format.html { redirect_to (post_url(@post, page: @current_page)), notice: 'Post was successfully created.' } format.json { render :show, status: :created, location: @post } else format.html { render :new } format.json { render json: @post.errors, status: :unprocessable_entity } end end end # PATCH/PUT /posts/1 # PATCH/PUT /posts/1.json def update @post.user = User.find_by email: params[:email] respond_to do |format| if @post.update(post_params) format.html { redirect_to (post_url(@post, page: @current_page)), notice: 'Post was successfully updated.' } format.json { render :show, status: :ok, location: @post } else format.html { render :edit } format.json { render json: @post.errors, status: :unprocessable_entity } send end end # DELETE /posts/1 # DELETE /posts/1.json def destroy @post.destroy respond_to do |format| format.html { redirect_to posts_url(page: @current_page), notice: 'Post was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_post @post = Post.find(params[:id]) end def set_current_page @current_page = params[:page] || 1 end # Never trust parameters from the scary internet, only allow the white list through. def post_params params.require(:post).permit(:title, :body, :page) end end end |
how to pass Constraint variables into helpers Posted: 31 Oct 2016 05:50 AM PDT We host a multi-domain environment and use constraints for the routing, to decide which domain it is. constraints DomainRouting.new("something.local", "something.com") do devise_for :users, controllers: { registrations: "registrations" } scope "mods" do defaults game: "mygame" do get "/*permalink", to: "mods#show", as: :mod, constraints: ModConstraint.new(:something) get "/*permalink", to: "categories#show", as: :category, constraints: CategoryConstraint.new(:something) end root to: "categories#index" end get "/", to: redirect("/mods") end how can i call category_path(cat) let's say in a mailer, where we don't have any request object available? so we need to be able to call that path for the correct domain, but i can't figure a way to do. rails5 |
rails heroku db:seed not going through Posted: 31 Oct 2016 04:56 AM PDT I recently destroyed my Player model, and generated a User model, with pretty much the same fields except the User one has username:string, email:string, password:digest . I also have a Blog model which is in a one-to-many relationship with the User model (previously with the Player model). class User < ApplicationRecord has_many :blogs, dependent: :destroy end class Blog < ApplicationRecord belongs_to :user end Problem is, on Heroku console, the Blog model still has player_id field from before. Blog(id: integer, player_id: integer, content: text, created_at: datetime, updated_at: datetime) I can run heroku run rails db:migrate , but when I try to run heroku run rails db:seed , it gives me this error. ActiveModel::MissingAttributeError: can't write unknown attribute `user_id` What does this mean? |
StripeJS error: This customer has no attached payment source Posted: 31 Oct 2016 05:19 AM PDT This question has been asked before but there is no prominent solution on either of the links and the problem still persists after trying all the methods provided in the links. I am trying to generate a stripe subscription plan and each time I go through the process I get the error as "This customer has no attached payment source." As you can see in the screenshot that the stripe_card_token also gets generated and I have console.log the token also from JS and that also gets generated. I have attached all the relevant code files. Github link for this project: https://github.com/arpit016/picture-app Stripeerror screenshot user.rb file class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable belongs_to :plan attr_accessor :stripe_card_token def save_with_payment if valid? customer = Stripe::Customer.create( :source => stripe_card_token, :email => email, :plan => plan_id ) self.stripe_customer_token = customer.id save! end end end users.js file $(document).ready(function() { Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content')); $('#form-submit-btn').click(function(event) { event.preventDefault(); $('input[type=submit]').prop('disabled', true); var error = false; if (!error) { Stripe.card.createToken($('#new_user'), stripeResponseHandler); } return false; }); //form submission function stripeResponseHandler(status, response){ if (status == 200){ //Get a reference to the form var f = $('#new_user'); //Get the token from the response var token = response.id; console.log("Token:" + token); //Add the token to the form f.append('<input type="hidden" name="user[stripe_card_token]" value="' + token + '" />'); console.log(f) //Submit the form f.get(0).submit(); } else { $('#stripe_error').text(response.error.message).show(); $('input[type=submit]').attr('disabled', false) } } }); Devise Modified Registrations controller class Users::RegistrationsController < Devise::RegistrationsController before_filter :select_plan, only: [:new] def create super do |resource| if params[:plan] resource.plan_id = params[:plan] if resource.plan_id == 2 resource.save_with_payment else resource.save end end end end def select_plan unless params[:plan] && (params[:plan] == '1' || params[:plan] == '2') flash[:warning] = "Please select a valid membership" redirect_to root_url end end end |
Should my tests be creating db records for manditory associations? Posted: 31 Oct 2016 05:02 AM PDT This is a best-practices kind of question: If my Garden has a required field of user_id should my tests be actually creating the User in the database, or is there a better approach? I'm finding that in my controller's update tests I'm running into cases where I want to reuse my garden factory, but the garden factory creates the required user in the database and I'm running into unique constraint violations on duplicate emails. So now I either need to make the factory generate unique emails or I need to learn how to mock up the associated record. I guess the thing that really has me caught up short is that creating/updating a garden checks the database for the existence of the associated record. I don't yet understand how I could shortcut that. And I also don't know if that is necessary? If I set up the database_cleaner gem to perform tests as database transactions by default, perhaps I don't have to worry about how many User records are being "written"? |
Rails + Ajax render multiple time during while loop Posted: 31 Oct 2016 04:08 AM PDT I have a form that is send asynchronously thanks to remote: true Inside my controller I have a loop because it needs to execute some particular action multiple times. Today I render only the result when the loop is finished and it's working but I would like to be able to render a progression each loop time, but when I use respond_to inside the loop there is an error AbstractController::DoubleRenderError (Render and/or redirect were called multiple times in this action.) I also already tried with render_to_string but nothing shows up. How can I bypass that to render a progression percentage (for example) of the loop to the view? My controller def run while condition # perform some actions render_to_string :partial => "static_pages/message_sent", :locals => { :message_sent => "Some text<br />" } respond_to do |format| format.js{ render :partial => "static_pages/message_sent", :locals => { :message_sent => "Some text<br />" } } end end end My view <%= form_tag("/run", method: "post", remote: true) do %> # Some form inputs <%= submit_tag("Start", :id => "start_script", data: { disable_with: "Wait..." }) %> <% end %> <br /><br /> <h3>Result :</h3> <div id="script_output"></div> Partial _message_sent.html.erb $('#script_output').append("DOES IT SHOWS UP?"); # No it doesn't run.js.erb (working only when the loop ends) $('#script_output').append("<%= @output.html_safe %>") |
How precompile css3 include attribute Posted: 31 Oct 2016 05:03 AM PDT I have a css: .answer_meta_outer { border-bottom: 1px dashed #ababab; margin: 0 0 45px; &:after { @include clr; } } I got a error: rake aborted! Sass::SyntaxError: Undefined mixin 'clr'. File name is app/assets/stylesheets/responsive.css Help me fix it please :) |
Carrierwave - File not removed automatically when changing upload directory Posted: 31 Oct 2016 03:53 AM PDT I'm using Carrierwave for file upload in my Rails app. I followed the How-To Secure Upload guide to secure my uploads. It works perfectly, but the uploaded file is not removed when it's owner (the model using the uploader) is destroyed. I get no error messages, the file is just left where it was uploaded. I tried changing it back to upload files to public/uploads and files are removed as they should. |
Lookup with dynamic parameter in Rails Posted: 31 Oct 2016 04:37 AM PDT In my Rails 5 application I need to be able to lookup data based on the type of the incoming params[:id] value that is being send from a 3rd party app. Each Model has two unique identifiers: id and cuid , and the received value can be either one of them. The problem is easily is illustrated like this: if params[:id][/^\d+$/] # if it is numeric @shipment = Shipment.find(params[:id]) elsif params[:id].present? @shipment = Shipment.find_by_cuid(params[:id]) end In the routes I have to define what parameter to use for lookup, e.g.: resources :shipments, param: :cuid But that ofc doesn't do the trick if I need to be able to lookup dynamically in both columns based on the data-type (and yes, I know that the incoming type will always be string by default). |
Calling Google Drive API using Ruby on Rails Framework Posted: 31 Oct 2016 03:19 AM PDT I am trying to get this code to work which is mentioned as example on Google-auth-library-ruby require 'googleauth' require 'googleauth/web_user_authorizer' require 'googleauth/stores/redis_token_store' require 'redis' client_id = Google::Auth::ClientId.from_file('/path/to/client_secrets.json') scope = ['https://www.googleapis.com/auth/drive'] token_store = Google::Auth::Stores::RedisTokenStore.new(redis: Redis.new) authorizer = Google::Auth::WebUserAuthorizer.new( client_id, scope, token_store, '/oauth2callback') get('/authorize') do # NOTE: Assumes the user is already authenticated to the app user_id = request.session['user_id'] credentials = authorizer.get_credentials(user_id, request) if credential`enter code here`s.nil? redirect authorizer.get_authorization_url(login_hint: user_id, request: request) end # Credentials are valid, can call APIs # ... end get('/oauth2callback') do target_url = Google::Auth::WebUserAuthorizer.handle_auth_callback_deferred( request) redirect target_url end in the get '/authorize' method is always nil even the user is logged in and authenticated using Devise Gem and Google Oauth2 gem . Can anyone may be share an example in rails framework how to obtain subsequent authorizations from Google to access any of their apis for which the user has given consent Even the ruby methods used on the Google website seems to have been deprecated so not finding much information online Thank you in advance |
How to restrict upload image type in tinymce-rails? Posted: 31 Oct 2016 05:16 AM PDT I am using (Rails 5): gem 'tinymce-rails', '>= 4.4.0' gem 'tinymce-rails-imageupload', '~> 4.0.0.beta' I would like to somehow restrict the filetype of an uploaded image - as JPEG, PNG, GIF etc. Now the user can upload any filetype (even non-images) - with any extension. How to do that correctly? |
Rails 5: edit user roles in single view Posted: 31 Oct 2016 05:06 AM PDT I have view where current_user can select its users and edit their roles. I'm struggling to create single view (without loading edit path) where on user select from drop-down, particular role info is shown and can be edited. In /controllers/common/roles_controller.rb I have this code, which in Index allows to find users and then I go to Edit: def index @users = User.joins(:accounts).where("accounts.company_id IN (?)", current_user.companies.pluck(:id)).distinct end def edit @role = Role.find(params[:id]) end private def correct_role redirect_to(errors_path) unless current_user.company_user_roles.where(id: params[:id]).exists? end def role_params params.require(:role).permit(:general, :dashboard, ../different params/.., user_id) end In /views/common/roles/index.html.erb I have this, however I'm not sure if this is the most effective and correct way: <% @users.each do |user| %> <% for role in user.roles %> <option value="<%= role.id %>" data-edit-url="<%= edit_common_role_path(role.id) %>"><%= user.name %></option> #Here below I have JS, which on user select go to particular user role edit which basically allows on user select go to particular role edit. I can edit role with this /views/common/roles/edit.html.erb code: <%= form_for([:common, @role]) do |f| %> <%= f.select :general, Role.generals.to_a.map { |w| [w[0].humanize, w[0]] }, {}, {class:"form-control m-b"} %> <%= f.select :dashboard, Role.dashboards.map { |w| [w[0].humanize, w[0]] }, {}, {class:"form-control m-b"} %> In /models/role.rb I have this: class Role < ApplicationRecord belongs_to :user, optional: true, inverse_of: :roles accepts_nested_attributes_for :user validates :user_id, presence: true enum general: { seller: 1, buyer: 2, seller_buyer: 3}, _suffix: true enum dashboard: { denied: 0, viewer: 1, editer: 2, creater: 3, deleter: 4}, _suffix: true #More enum columns follow here... There are column user_id in roles table. In /models/company.rb I have this: class Company < ApplicationRecord has_many :accounts, dependent: :destroy has_many :users, through: :accounts has_many :user_roles, through: :users, source: :roles In /models/account.rb I have this: class Account < ApplicationRecord belongs_to :company belongs_to :user accepts_nested_attributes_for :company, :user end How to do I create single view where roles of particular user are loaded and then can be edited? Thank you for help or any hint! |
Rails has_and_belongs_to_many on 2 level association Posted: 31 Oct 2016 02:26 AM PDT This is related to this previously asked question I have a has_and_belongs_to_many in place between Product and Supplier. In my view I use: <td><%= product.suppliers.map {|supplier| supplier.NAME }.join(', ') %></td> To show list of suppliers comma separated on each row for each product in my table. I now need to show the same list on invoices index view. Invoices table has a column PRODUCT. I have already set belongs_to :product on Invoice model. I tried in my invoices index view: <td><%= invoice.product.suppliers.map {|supplier| product.supplier.NAME }.join(', ') %></td> but it returns error undefined local variable or method `product' Why isn't that working? How can I fix it? Thanks in advance. |
Layout for admins and users Login page Posted: 31 Oct 2016 02:18 AM PDT I have admin user authentication with devise I generated devise for user and one for admin and i am making layout using main devise layout page here is my route file devise_for :admins devise_scope :admin do get '/admins/sign_out' => 'devise/sessions#destroy' authenticated :admin do root 'home#index' end # delete "/logout" => "devise/sessions#destroy" end devise_for :users devise_scope :user do get '/users/sign_out' => 'devise/sessions#destroy' authenticated :user do root 'user_home#index', as: :authenticated_root end unauthenticated do root 'devise/sessions#new', as: :unauthenticated_root end end I want to differentiate between the title of the admin page and the user page login. Thanks a lot |
Koala support for multiple FB Apps at the same time? Posted: 31 Oct 2016 12:03 AM PDT I'm initializing Koala with one FB App's info (app id, secret, callback url) and that is the usual one that I need to use for making graph api calls. However, I need to occasionally make calls within the same RoR process to the FB graph api for a different FB App. What's the best way to do this for one-off calls that I need to make for the 2nd FB App? I thought initializing a new object like this would work, but it still seems to be using the original app info: k = Koala::Facebook::API.new(user_fb_token, APP_2_SECRET) Ideally, it can support multiple apps at the same time so that I don't have to worry about other calls accidentally using the 2nd app if I re-initialize Koala. |
How to paginate users with more than 0 object of attribute boolean: false? Posted: 31 Oct 2016 12:49 AM PDT How to paginate users with more than 0 publish challenges? controller Attempt 1 @users, @alphaParams = User .select{ |user| user.challenges.publish > 0 } .alpha_paginate(params[:letter], {:pagination_class => "pagination-centered"}){|user| user.name} Attempt 2 @users, @alphaParams = User .where(self.challenges.publish > 0) .alpha_paginate(params[:letter], {:pagination_class => "pagination-centered"}){|user| user.name} Attempt 3 @users, @alphaParams = User.joins(:challenges) .where('challenges.publish > 0') .distinct .alpha_paginate(params[:letter], {:pagination_class => "pagination-centered"}){|user| user.name} model scope :publish, ->{ where(conceal: false) } |
How to show forgot error messages in a modal with devise functionality? Posted: 31 Oct 2016 12:07 AM PDT I am having a login form where there is a forgot password link and when we click on that a Modal pop-up appears where we enter our email address. This is fine when we enter the correct / existing email but if we enter any wrong email or the email doesn't exist in database, it is not showing any error message. Please help. I tried using <%= devise_error_messages! %> but no use. I think we have to use jQuery / javascript functionality inorder to show error. But how to show on the model itself? This is my view: <div class="container"> <div class="section section-signup"> <%= semantic_form_for(@resource, :as => resource_name, :url => user_session_path, :remote => true, :format => :json, :html => { :id => 'mainLogin' }) do |f| %> <%= f.inputs do %> <%= f.input :email, :label => 'Your email address', :input_html => { :placeholder => "Email"} %> <%= f.input :password, :label => 'Your password', :input_html => { :placeholder => "Password"} %> <% end %> <%= f.buttons do %> <% if devise_mapping.rememberable? %> <%= f.input :remember_me, :as => :boolean, :label => "Remember me on this computer", :required => false, :input_html => {:class => "remember-me"} %> <% end %> <%= f.commit_button :label => 'Sign me in', :button_html => {:class => 'login submit button', :disable_with => 'Wait...', :id => 'user_submit' }%> <% end %> <div class="forgot">Yikes: <a class="pass-reset-btn cboxElement" href="#pass-reset" data-toggle="modal" data-target="#myModal">I forgot my password!</a></div> <% end %> </div> </div> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title" id="myModalLabel">Password reset</h4> </div> <div class="modal-body"> <p>Enter your email address and we'll shoot you a link for resetting your password.</p> <!-- Start Fromtastic Markup --> <%= semantic_form_for(resource_name, :url => password_path(resource_name), :remote => true, :format => :json, :html => { :id => 'password_reset' }) do |f| %> <%= f.inputs do %> <%= f.input :email, :label => 'Your email address', :input_html => { :placeholder => "Enter your email..."}%> <% end %> <%= f.buttons do %> <%= f.commit_button :label => 'Send me that link', :button_html => {:class => 'submit button', :disable_with => 'Wait...' }%> <% end %> <div class="clearfix"></div> <% end %> <!-- End Fromtastic Markup --> </div> </div> </div> </div> |
No comments:
Post a Comment