Facebook omniauth: Ensure unique username Posted: 03 Dec 2016 08:18 AM PST I have an app with user authentication with devise + omniauth. In my User model I want to ensure that the user.name is unique, so that there are no duplicate usernames in my app. After looking around I came up with the following code: User.rb def ensure_username_uniqueness uniqname = (self.name).dup num = 1 until(User.find_by(name: uniqname).nil?) binding.pry ## test tool: shows the line above is not executed ## uniqname = self.name+"-#{num}" num += 1 end self.name = uniqname end private def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.provider = auth.provider user.uid = auth.uid user.email = auth.info.email user.password = Devise.friendly_token[0,20] user.name = auth.info.name[0..29].downcase.gsub(" ", "-") user.ensure_username_uniqueness user.remote_avatar_url = auth.info.image user.skip_confirmation! end end When I test Facebook registration with a name that already exists in the database, the I get redirected to the sign up page (meaning sign up failed). I set a binding.pry and noticed that the code doesn't execute the until loop. I tried changing to the same logic with a while loop but no luck. I can't seem to understand why this code fails. Any help would be much appreciated! |
Explanation on Rails Associations - Rails 4 Posted: 03 Dec 2016 07:56 AM PST i'm new to rails and your help and advise would be much appreciated as i am finding this challenging Aim: i want the creator of the event to be able to select more than one user as hosts for a created event (just like how facebook allows the creator of a page to be be able to select users as admins of a created page). Is the below how my model and schema should be displayed? i was aiming to build something like this image. Event1 i can select Ian & Jesse as hosts, Event2 i can also select Ian again as a host and select Emma This is how i imagine it so far to be built (your guidance would be much appreciated): models user.rb has_many events event.rb belongs_to user host.rb belongs_to user has_many events schema users name email events title address user_id hosts user_id event_id |
Is there a ruby library to generate Bootstrap components? Posted: 03 Dec 2016 07:51 AM PST It seems like there ought to be a library out there that will make it easier to generate the view markup for various bootstrap components. Perhaps this exists, but the prevalence of the bootstrap gem makes it hard to google for. For clarity, what I'm imagining is a library that would allow me to do something like this: .container .row - @gardens.each do |garden| -@bootstrap.card(img: "http://lorempixel.com/g/400/200/food/", title: garden.name) instead of this: .container .row - @gardens.each do |garden| .col-md-3 .garden.card .card-block %h4.garden__title.card-title= garden.name .card-img-bottom= image_tag("http://lorempixel.com/g/400/300/food") Does such a thing exist? |
How to pass a variable to modal from a for loop Posted: 03 Dec 2016 07:58 AM PST I have for loop where I call a partial for each iteration of the loop: <% applications.each do |application| %> <td> <%= render :partial => "layouts/form", :locals => {:@application => application} %> </td> <% end %> Now, within the partial, I have a button which when pressed would display a modal: <button type="button" class="button-custom btn-primary" data-toggle="modal" data-target="#form-modal"> <%= "#{button_text}" %> </button> <div id="form-modal" class="modal fade modal-form" role="dialog" tabindex='-1'> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <td> <%= "#{@application.name}" %> </td> The problem now is that @application.name always refers to the value of the first application within the for loop. It does not get the value corresponding the respective iteration of the loop. |
join tables in RoR Posted: 03 Dec 2016 07:24 AM PST I have the following two models. class ResponseMap < ActiveRecord::Base has_many :response, foreign_key: 'map_id', dependent: :destroy belongs_to :reviewer, class_name: 'Participant', foreign_key: 'reviewer_id' class Response < ActiveRecord::Base include ResponseAnalytic belongs_to :response_map, class_name: 'ResponseMap', foreign_key: 'map_id' I have to join these two models and find the responses given by a particular reviewer in ResponseMap such that response.map_id = responseMap.id. This is the SQL query i need to translate to an active record query for my ResponseMap model. select * from response_maps as rm join responses as r on r.map_id = rm.id where rm.reviewer_id = 97 Can anyone help me with this? |
What is the conventional architecture for a Rails 5 API with an Administrative UI as well? Posted: 03 Dec 2016 06:43 AM PST I was setting out to start a new Rails 5 API, and realized I also need a content-administration "site" of some sort. The admin tool is very simple, just a UI for very basic CRUD operations. I have an instinct to create two separate Rails applications - one web application for the content-admin tool, and another web application for the API. This brings about the problem with sharing data models, which is solvable by using rails engines, or including the models as a gem. As I was researching solutions, I seemed to observe a pattern of including the content-admin portion within the API app itself. There are some middleware includes and controller inheritances involved in this, but its quite simple to get a content-admin UI to run within the same app as an API. Its much less work, and I dont see much of a problem with scale, since the content-admin UI is lightly utilized and the API is the core of the business. Is this the accepted convention? I might be gaining a bias due to web search results, but it seems like the simplest and most common approach. I plan to have a separate server for accessing the content-admin vs accessing the API, which is what led me to originally plan this as two separate apps. Now I am thinking I was just getting sucked into the "microservices" hype, and it seems more conventional to just include the content-admin UI with my API app. On the other side, everything I read about Rails engines is 3-4 years out of date. There is little information (that I am stumbling upon) within the last year or so, and more specifically, little-to-no information concerning Rails 5. I am wondering if this sort of architecture has fallen by the wayside. Is there a typical convention for Rails 5 API applications that also need a content-admin UI? |
NoMethodError (undefined method `id' for nil:NilClass): in CarrierWave model Posted: 03 Dec 2016 08:03 AM PST I am using carrierwave to upload images in my rails project. This is my uploader class. class ProfilePictureUploader < CarrierWave::Uploader::Base def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end end I am not using mount_uploader :avatar , ProfilePictureUploader in my model . Instead I use this in my model uploader = ProfilePictureUploader.new uploader.store!(file) self.image = uploader.url self.save But this is giving me an error saying NoMethodError (undefined method `id' for nil:NilClass) Understandably the model instance is not available in ProfilePictureUploader . So store_dir method can't access model.id . How can I get a similar directory structure with this flow. This is not a duplicate of this problem . For me , the model attribute of uploader is not available. |
Ruby on rails redirect_to to an external url call the method twice Posted: 03 Dec 2016 06:30 AM PST I have a view that call a simple method of controller <p><%= link_to "Log In external app", login_with_external_app_path %></p> The controller does : def login_with_external_app params = {secret_key: ENV['SECRET_APP_KEY'], scope: 'x:y' } uri = URI('https://an_app.com/login/oauth/authorize') uri.query = params.to_query redirect_to(uri.to_s) end The method login_with_external_app is called twice. The first one is when I click on the button of my view, after clicking the piece of code is executed properly and it not redirects to the uri properly (the console shows me that the application found the URL ), after that the method is called again and it redirects fine. The console logs: Started GET "/login_with_external_app" for ::1 at 2016-12-03 11:23:11 -0300 Processing by SessionsController#login_with_external_app as HTML Redirected to https://an_app.com/login/oauth/authorize?secret_key=123456&scope=x%3y Completed 302 Found in 2824ms (ActiveRecord: 0.0ms) Started GET "/login_with_external_app" for ::1 at 2016-12-03 11:23:15 -0300 Processing by SessionsController#login_with_external_app as HTML |
Can't pass id to nested route Posted: 03 Dec 2016 05:52 AM PST For a personal achievment, I'm trying to create an online magazine to let people read some news I created two scaffolds, one for the manga and the other for its pages. I manage to create the magazine, upload its pages via a multi upload system thanks to the second scaffold. Then, I wanted the link for a magazine's page to look like domain.net/magazines/:id/pages/:id , however, I'm getting some difficulties that I don't seem to be able to solve by myself Here's my magazines#show view: <h4> <%= @magazine.titre %> </h4> <%= image_tag @magazine.apercu, size: '200x200' %> <% @magazine.pages.each do |m| %> <%= link_to magazine_page_url, :id => m.id do %> <!-- Here --> <%= image_tag m.image, size: '100x100' %> <% end %> <%= link_to m do %> <%= image_tag p.image, size: '100x100' %> <% end %> <%= link_to 'Supprimer', m, :method => :delete, data: {confirm: 'Are you sure?'} %> <% end %> <br /> <%= link_to 'Edit', edit_magazine_path(@magazine) %> | <%= link_to 'Back', magazines_path %> Whenever I try to get this page, I'm getting the following error: ActionController::UrlGenerationError in Magazines#show -- No route matches {:action=>"show", :controller=>"pages", :id=>"6"} missing required keys: [:magazine_id] As you can see, I'm trying to create a link around every magazine's pages to redirect to the pages itself, but I can't manage to give a proper id to the link. When I try to put <%= link_to m do %> instead of magazine_page_url , he's searching for a path named 'page_path', that doesn't exist since I nested the page resources inside my magazines resources. Here is my route file just in case, don't hesitate if you need to see something else Rails.application.routes.draw do root to: 'home#index' namespace :admin do resources :carousels end get '/admin' => 'admin#index', as: :admin_root resources :magazines do resources :pages end end Any help is welcome Thank you in advance |
decent_exposure with devise Posted: 03 Dec 2016 05:38 AM PST so i'm trying ti get a grasp on decent_exposure gem, as it is very praised by the community. nevertheless i have a hard time combining it with devise. Lets take a look: class TopicsController < ApplicationController expose :topic def new end def create respond_to do |format| if topic.save format.html { redirect_to root_path , notice: "success" } else format.html { render action: :new, alert: "no success:(" } end end end so in the show/new/create actions i can call topic() method and it will instantly give me either record based on params[:id], or a completely new one, not yet saved into the database. the question is how do i keep the decent exposure and connect the new topic with the current_user? i know i can pass the block into the expose method, but what if the topic already have a user, it would ruin my db. any suggestions? |
Rails server freezes in bash on ubuntu on windows Posted: 03 Dec 2016 05:07 AM PST I installed Ruby on bash on ubuntu on windows, and prepared my Rails project. (rvm 1.27.0, ruby 2.1.5, rails 4.1.1, with psql in windows itself) however when I start the rails server it freezes after completing the very first GET, its last message is as would be expected for normal work Completed 200 OK in 7394ms (Views: 7028.7ms | ActiveRecord: 109.9ms) but the page never gets rendered in the browser, and the rails freezes not responding even to CTRL+C, the only option is to close the bash window itself. I am not sure if it is relevant, but in the Windows task manager there appears a Ruby task occupying about 30% of the CPU which never stops. |
Ruby on Rails Convention over Configuration (CoC) Issues to scale Large Rails Project Posted: 03 Dec 2016 06:51 AM PST Working with Ruby on Rails for somewhile now. I'm enjoying it's builtin "Convention over Configuration" for small project. But, I'm little anxious about CoC application in Large Rails Projects. I know some pre built-in configuration raises more difficulty than ease, when need to scale the application in broad. What is those all specific Configurations will raise problem for me to scale? I will very grateful, if you please briefly explain those issues. |
Inbound parse hook not working on production Posted: 03 Dec 2016 03:40 AM PST I have setup an mx record using @ as host and points to mx.sendgrid.net I have also whitelabeled the account to reply.respiratoryexamprep.com I have create parse hook for "respiratoryexamprep.com" and pointed it to https://www.respiratoryexamprep.com/email_processor It does not work and i have been trying for a few days (the dns should be propagated by now). BUT if i change the hook to point to an ngrok url to test locally it works. Please advise Using Rails on Heroku. |
How to correctly move elements in tooltip Posted: 03 Dec 2016 04:00 AM PST i'm creating a like model in rails application. To show which user liked the bonus, i'm using foundation tooltip. Here is a code: - avatars = bonus.like_user_avatars.map { |avatar| image_tag(avatar) } span.has-tip.top data-tooltip="" data-template="<div class='tooltip'> <p>#{bonus.like_user_fullname.join(", ")}</p>#{avatars.join}</div>"Likes #{bonus.likes_count} The output html looks like: <span class="has-tip top" data-template="<div class='tooltip'> <p>Damir Nurgaliev, Damirikzrtyu Damirik</p><img src="https://lh4.googleusercontent.com/-mosfIn_6OMU/AAAAAAAAAAI/AAAAAAAAAEE/kR28SfgytTc/s64/photo.jpg" alt="Photo" /> <img src="https://lh6.googleusercontent.com/-rOyKmYUWNfs/AAAAAAAAAAI/AAAAAAAAABY/Nj3lXpqII9A/s64/photo.jpg" alt="Photo" /></div>" data-tooltip="r90rx1-tooltip" title="" aria-describedby="l150xr-tooltip" data-yeti-box="l150xr-tooltip" data-toggle="l150xr-tooltip" data-resize="l150xr-tooltip">Likes 2</span> I want to move each users full name under their avatar on tooltip. How can I do it? |
Grabbing a song uploaded via Paperclip, stored in S3, played with jPlayer (Ruby) Posted: 03 Dec 2016 06:59 AM PST I am struggling with the following: In my webapp, I am uploading mp3 files (or mpeg) via paperclip, which works on local. I am also linking the upload with Amazon S3, which also works (I can see in my bucket the uploaded songs, no errors on server side). So, the upload part works fine. Now, I am having a hard time "grabbing" my audio files and playing them via jPlayer, a jQuery based media player. I tested the player with a URL, and it works perfectly well. Here is what I've done, I am using ruby 2.3.0 and Rails 5. Model: class Episode < ApplicationRecord belongs_to :podcast has_attached_file :episode_thumbnail, styles: { large: "1000x1000#", medium: "550x550#" } validates_attachment_content_type :episode_thumbnail, content_type: /\Aimage\/.*\z/ has_attached_file :mp3 validates_attachment :mp3, :content_type => { :content_type => ["audio/mpeg", "audio/mp3"] }, :file_name => { :matches => [/mp3\Z/]} end I am also permitting the mp3 in my params: Controller: def episode_params params.require(:episode).permit(:title, :description, :episode_thumbnail, :mp3) end My form looks like this: <div class="field"> <%= f.label :mp3 %><br> <%= f.file_field :mp3 %> </div> Eventually, here is the script I am using with jPlayer, and that's where I think there's something wrong, that I can't figure out: <script> $(document).ready(function(){ $("#jquery_jplayer_1").jPlayer({ ready: function () { $(this).jPlayer("setMedia", { mp3: "<%= @episode.mp3.url %>"; }); }, swfPath: "/js", supplied: "mp3" }); }); </script> The view of the player looks like this: <!-- jPlayer --> <div id="jquery_jplayer_1" class="jp-jplayer"></div> <div id="jp_container_1" class="jp-audio"> <div class="jp-type-single"> <div class="jp-gui jp-interface"> <div class="jp-controls"> <li><a href="javascript:;" class="jp-play" tabindex="1">񑘕</a></li> <li><a href="javascript:;" class="jp-pause" tabindex="1">񑘕</a></li> <li><a href="javascript:;" class="jp-mute" tabindex="1">񑘕</a></li> <li><a href="javascript:;" class="jp-unmute" tabindex="1">񑘕</a></li> </div> <div class="jp-progress"> <div class="jp-seek-bar"> <div class="jp-play-bar"></div> </div> </div> <div class="jp-volume-bar"> <div class="jp-volume-bar-value"></div> </div> <div class="jp-time-holder"> <div class="jp-current-time"></div> </div> </div> <div class="jp-no-solution"> <span>Update Required</span> To play the media you will need to either update your browser to a recent version or update your <a href="http://get.adobe.com/flashplayer/" target="_blank">Flash plugin</a>. </div> </div> </div> <!-- end jPlayer --> In my opinion, the <%= @episode.mp3.url %> can be the problem here, once again, I've tried with a random URL storing a MP3 file, and it works well. Any thoughts on this will be much appreciated. Thanks in advance. |
How and where Sidekiq tests are supposed to be created? Posted: 03 Dec 2016 05:36 AM PST If a job is created with Active Job using the Rails generator, automatically a test for that job is created in test/jobs. Otherwise, both job and test can be manually created and put respectively in app/jobs and test/jobs. The test inherits from ActiveJob::TestCase Is it possible to create a workers (or sidekiq ) directory under test and put there all my Sidekiq tests? Also, where my sidekiq tests are supposed to inherit from? Basically my jobs periodically update models attributes, and I would like to use all three testing modes: fake , inline and disable . Some of these changes are visible in the web interface, so I could use an integration test. Other changes are not visible via web, so using in this case an integration test seems to me improper. Would in this case inherit directly from Minitest::Test be correct? Where in the working tree these tests are supposed to go? |
ArgumentError too few arguments when trying to test the controller Posted: 03 Dec 2016 05:20 AM PST I'm trying to learn how to do tests in Rails. I have a foods_controller and in the test folder, my food.yml is filled with all of the parameters that should be present when creating a new food object and in foods_controller_test.rb , the parameters in "should create food" are matching the ones in food.yml . When running a test I get this error: ArgumentError: too few arguments app/controllers/application_controller.rb:45:in `format' app/controllers/application_controller.rb:45:in `authorize' test/controllers/foods_controller_test.rb:21:in `block (2 levels) in <class:FoodsControllerTest>' test/controllers/foods_controller_test.rb:20:in `block in <class:FoodsControllerTest> Can anyone exaplain me what is wrong here? food.yml one: name: "Whatever" portion: "100g" calories: 1 fat: 1.5 carb: 1.5 protein: 1.5 fiber: 1.5 sugar: 1.5 category: "Grains" two: name: "MyString" portion: "MyString" calories: 1 fat: 1.5 carb: 1.5 protein: 1.5 fiber: 1.5 sugar: 1.5 category: "MyString" foods_controller_test.rb require 'test_helper' class FoodsControllerTest < ActionController::TestCase setup do @food = foods(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:foods) end test "should get new" do get :new assert_response :success end test "should create food" do assert_difference('Food.count') do post :create, food: { calories: @food.calories, carb: @food.carb, category: @food.category, fat: @food.fat, fiber: @food.fiber, name: @food.name, portion: @food.portion, protein: @food.protein, sugar: @food.sugar } end assert_redirected_to food_path(assigns(:food)) end test "should show food" do get :show, id: @food assert_response :success end test "should get edit" do get :edit, id: @food assert_response :success end test "should update food" do patch :update, id: @food, food: { calories: @food.calories, carb: @food.carb, category: @food.category, fat: @food.fat, fiber: @food.fiber, name: @food.name, portion: @food.portion, protein: @food.protein, sugar: @food.sugar } assert_redirected_to food_path(assigns(:food)) end test "should destroy food" do assert_difference('Food.count', -1) do delete :destroy, id: @food end assert_redirected_to foods_path end end foods_controller.rb class FoodsController < ApplicationController before_action :set_food, only: [:show, :edit, :update, :destroy] before_filter :authorize, only: [:create, :delete] # GET /foods # GET /foods.json def index @foods = Food.order(:name) # @foods = @foods.sort_by &:name # @users.sort! { |a,b| a.name.downcase <=> b.name.downcase } @food_categories = Food::CATEGORIES.keys.sort # @current_category ||= params(:category) day_selected = params[:day_selected] meal_selected = params[:meal_selected] end # GET /foods/1 # GET /foods/1.json def show end # GET /foods/new def new @food = Food.new end # GET /foods/1/edit def edit end # POST /foods # POST /foods.json def create @food = Food.new(food_params) respond_to do |format| if @food.save format.html { redirect_to foods_url, notice: 'Food was successfully created.' } format.json { render :show, status: :created, location: @food } else format.html { render :new } format.json { render json: @food.errors, status: :unprocessable_entity } end end end # PATCH/PUT /foods/1 # PATCH/PUT /foods/1.json def update respond_to do |format| if @food.update(food_params) format.html { redirect_to foods_url, notice: 'Food was successfully updated.' } format.json { render :show, status: :ok, location: @food } else format.html { render :edit } format.json { render json: @food.errors, status: :unprocessable_entity } end end end # DELETE /foods/1 # DELETE /foods/1.json def destroy #current_user.entries.where(food_id: "#{@food.id}").delete_all @food.destroy respond_to do |format| format.html { redirect_to foods_url, notice: 'Food was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_food @food = Food.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def food_params params.require(:food).permit(:name, :portion, :calories, :fat, :carb, :protein, :fiber, :sugar, :category, :added_by, :cholesterol, :potassium, :sodium, :trans_fat, :monounsaturated_fat, :polyunsaturated_fat, :saturated_fat) end end food.rb class Food < ActiveRecord::Base belongs_to :user CATEGORIES = { "Dairy & Eggs" => "Dairy", "Meat & Fish" => "Animal", "Fruits & Vegetables" => "Plant", "Nuts, beans & legumes" => "Nuts", "Grains" => "Grains", "Drinks" => "Beverages", "Sweets & Candy" => "Sweets", "Oils & Fats" => "Oils", "Other" => "Other" } validates :name, presence: true validates :portion, presence: true validates :calories, presence: true validates :fat, presence: true validates :carb, presence: true validates :protein, presence: true validates :category, presence: true end |
Complex Rails Association Posted: 03 Dec 2016 05:20 AM PST Not sure which association best fits what I want. Basically it's a todo list. The list is a task and that task has many users. ie: Dig a hole and plant some seeds. Digging a hole will require two or more people. Jim and Jo are digging the hole and Jo will plant the seeds after. So two lists to complete, the first by two users and the other by one. Both user can complete both lists if needed. - Todo: has many lists
- List: belongs to todo
- List: has many users
- User: has many lists
If Im not clear, each task (list) on a todo can be completed by any user. I struggle to see where to put a list_id on the users table. That's not possible as that user can be doing another (list) at the same time. Im not sure how through: :association comes into play here. User.first.lists #= [] Todo.first.lists.first.users #= [] I get nothing as the user_id needs to go somewhere. |
Json jbuilder: if many times reload page, page reload very slowly Posted: 03 Dec 2016 01:33 AM PST I pass data in json to frontend. I am using gem jbuilder. #controllers/api/curtains_controller.rb module Api class CurtainsController < ApplicationController def index @curtain_types = Shop::CurtainType.all end end end #views/api/curtains/index.json.jbuilder json.curtain_types @curtain_types do |type| json.id type.id json.name type.title json.image type.image json.needCornice type.cornice json.fabrics type.fabrics do |fabric| json.title fabric.title json.image fabric.image json.shade_fabrics fabric.shade_fabrics do |shade_fabric| json.id shade_fabric.id json.title shade_fabric.title json.image shade_fabric.image end end end json.mountains Shop::Mountains.each do |key, enum| json.title enum.value end link is http://localhost:3000/api/curtains.json Data passes in json format. All good, but if many times reload html page wich take data trough curtains.json page load very slowly, can 1 min. |
Rails: Elegant way to find name from related model Posted: 03 Dec 2016 12:49 AM PST I have to models: Father has_many Children f_name Child belongs_to Father c_name father_id(fk) In children's index page I want to show c_name and fathers' name <% @children.each do |child|%> <%= child.name %> <% if Father.find(child.father_id) %> <%= Father.find(child.father_id).f_name %> <% end %> <% end %> I do not think the code is elegant. Maybe I should put them into helper or model, but I do not know how to do that. Anybody help will be appreciated. |
Rails Capstrano rvm method_missing Posted: 03 Dec 2016 01:17 AM PST I want to deploy Rails app to AWS EC2 by using capstrano , but after I type cap production deploy , I found following error in console. DEBUG [309bdf2a] Command: cd /home/ubuntu/MY_APP/releases/20161203071428 && ~/.rvm/bin/rvm 2.3.1@rails5.0.0.1 do passenger -v DEBUG [309bdf2a] /home/ubuntu/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/rubygems/specification.rb:2158:in `method_missing' DEBUG [309bdf2a] undefined method `this' for #<Gem::Specification:0x9b54b0 passenger-5.0.30> I thought the problem is cause by rvm or passenger , but I am not sure is it the problem of permission or path. Here is the setting in deploy/production.rb set :rvm_type, :auto set :rvm_ruby_version, '2.3.1@rails5.0.0.1' set :passenger_rvm_ruby_versionw I also put the following code in in the Capfile. require 'capistrano/rvm' require 'capistrano/bundler' require 'capistrano/rails/assets' require 'capistrano/rails/migrations' require 'capistrano/puma' require 'capistrano/passenger' If you need more information, please let me know! Here is the whole error message https://gist.github.com/fifiteen82726/62cc9ce9a5c00778c2bff76e3fb59b9a |
Seeding with unique objects Posted: 02 Dec 2016 11:33 PM PST I'm trying to seed my database with project with unique project name, however my seeder does not work as I intended. Seed.rb users = User.order(:created_at).take(6) 50.times do |n| name = "project-#{n+1}" category = "category-#{n+1}" users.each { |user| user.projects.create!(name: name, category: category) } end If I remove validates :name, presence: true, uniqueness: true it will create 50 projects for each user from 1 to 50, but then for the next user would do the same (count resets) and will create projects with titles from 1 to 50 which interferes with the validates rule. Any ideas? |
Can I download a CSV file with `remote: true` on a Rails form? Posted: 02 Dec 2016 10:46 PM PST I'm building a very simple single-page Rails app with a single form using the remote: true option. Basically, the use selects a few options on the form, and I render a set of products matching these requirements back to the page using the create.js.erb view. So far, so good. I'd also like to give the user the option to download a CSV list of the products. The problem is, with the remote: true option, I can't figure out how to actually trigger the download. I can use the hack here to route to the correct format and action: <%= button_tag( 'Download CSV', :value => 'csv', :name => 'format' ) %> def create respond_to do |format| format.js format.csv { send_data @products.to_csv } end end This almost works; the correct CSV (text) data is returned in the browser response when I click the "Download CSV" button -- but it doesn't get rendered or trigger a file download, presumably because it's being returned in an AJAX response. I could make this work by using a link, rather than submitting the form (assuming the action responds to 'GET'): <%= link_to 'Download CSV', products_path(format: :csv) %> But then I don't have access to the user data about the product requirements captured in the form parameters. Is there any way to make this work, or do I need to lose the remote: true and submit the form via HTML (non-AJAX) to trigger the CSV download? |
Rails how to use infinite scroll with datagrid and datatable? Posted: 02 Dec 2016 09:48 PM PST I have a problem while using infinite scroll with datagrid. I want to do infinite scroll when scrolling to the bottom of the table and fetch the next page data. I'm using jquery infinite scroll + kaminari gem, dataTable and Datagrid. - if i'm scrolling to the bottom of the table, its fetch new page data correctly.
- but when i filterd some columns (using datagrid), its fetch the next page data and looping the same data again and again when i'm scrolling to the bottom.
- its working as normal if i don't filtered with datagrid.
gem & js library gem 'datagrid' gem 'jquery-datatables-rails' gem 'kaminari' https://github.com/infinite-scroll/infinite-scroll controller respond_to do |f| f.html do @client_grid.scope { |scope| scope.accessible_by(current_ability).page(params[:page]).per(20) } end f.js do @client_grid.scope { |scope| scope.accessible_by(current_ability).page(params[:page]).per(20) } end end view .col-xs-12 .ibox-content .clients-table %table.table.table-bordered.table-striped.table-hover.clients %thead = datagrid_header(@client_grid) %tbody.page = render 'client_rows' .ibox-footer.text-center.hidden = paginate @client_grid.assets Coffee $("table.clients .page").infinitescroll navSelector: "ul.pagination" # selector for the paged navigation (it will be hidden) nextSelector: "ul.pagination a[rel=next]" # selector for the NEXT link (to page 2) itemSelector: "table.clients tbody tr" # selector for all items you'll retrieve loading: { img: 'http://i.imgur.com/qkKy8.gif' msgText: '<em>Loading clients...</em>' } donetext: "<em>You've reached the end.</em>" binder: $('.clients-table .dataTables_scrollBody') |
Rails with Devise, omniauth-google-oauth2 and omniauth-linkedin-oauth2 Authentication failed Posted: 02 Dec 2016 09:46 PM PST I am using omniauth-oauth2 ,omniauth-google-oauth2 ,omniauth-linkedin-oauth2 ,omniauth-facebook ,omniauth-twitter gems for Authentication of my basic rails app hosted in aws ec2.Facebook and Twitter Authentication is working fine but while Authentication with Linkedin and google+ are rendering the message "Not found. Authentication passthru." Facebook and Twitter are working fine.please help me with the problem .Any help is highly Appreciated. Thanks in Advance. Gemfile ruby '2.3.1' gem 'devise', '~> 4.2' gem 'koala', '~> 2.4' gem 'linkedin', '~> 1.1' gem 'omniauth-oauth2', '~> 1.4' gem 'omniauth-facebook' gem 'omniauth-google-oauth2' gem 'omniauth-twitter' gem 'omniauth-linkedin-oauth2', '~> 0.1.5' devise.rb config.omniauth :facebook, "356781xxxxx", "1686997c451aecfd12dc7bxxxxxx", scope: 'email', info_fields: 'email', callback_url: "http://ec2-xx-xxx-xx-xx.us-west- 2.compute.amazonaws.com/users/auth/facebook/callback" config.omniauth :twitter, "HnA4m6IzaZ1haT9nxxxxxxx", "SsL6TiWFLkKDWnta5zRek7YBvwfPBfMEiNYWRVxxxxxxxxxxx", callback_url: "http://ec2-xx-xxx-xx-xx.us-west- 2.compute.amazonaws.com/users/auth/twitter/callback" config.omniauth :google_oauth2,"115059498414- 5fj2in117vueg4a1tdg52xxxxxxxxx.apps.googleusercontent.com"," ZbPzUjSKpYRTmxxxxxxx", { :name => "google", :scope => "email, profile, plus.me", :prompt => "select_account", :image_aspect_ratio => "square", :info_fields => "id,name,link", :image_size => 50 } require "omniauth-linkedin-oauth2" config.omniauth :linkedin, "811sfhxxxxxx","Pe2wtfRbxxxxx",:scope => 'r_fullprofile r_emailaddress' users/omniauth_callbacks_controller.rb class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController skip_before_action :verify_authenticity_token def sign_in_with(provider_name) @user = User.from_omniauth(request.env["omniauth.auth"]) sign_in_and_redirect @user, :event => :authentication set_flash_message(:notice, :success, :kind => provider_name) if is_navigational_format? end def facebook sign_in_with "Facebook" end def linkedin sign_in_with "LinkedIn" end def twitter sign_in_with "Twitter" end def google_oauth2 sign_in_with "Google" end def developer sign_in_with "Developer" end end user.rb class User < ActiveRecord::Base devise :rememberable, :trackable, :omniauthable, :omniauth_providers => [:twitter,:facebook, :linkedin_oauth2, :google_oauth2, *(:developer if Rails.env.development?)] def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| user.email = auth.info.email end end end routes.rb Rails.application.routes.draw do devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" } devise_scope :user do get 'sign_in', :to => 'devise/sessions#new', :as => :new_user_session delete 'sign_out', :to => 'devise/sessions#destroy', :as => :destroy_user_session end root 'home#index' end callback URL to my app site in google developer account: Authorized JavaScript origins : http://ec2-xx-xxx-xx-xx.us-west Authorized redirect URIs : ec2-xx-xxx-xx-xx.us-west/users/auth/google/callback also tried with ec2-xx-xxx-xx-xx.us-west/users/auth/google_oauth2/callback callback URL to my app site in linkedin developer account: OAuth 2.0 Authorized Redirect URLs: ec2-xx-xxx-xx-xx.us-west/users/auth/linkedin/callback ec2-xx-xxx-xx-xx.us-west/users/auth/linkedin_oauth2/callback even tried with OAuth 1.0a Default "Accept" Redirect URL: ec2-xx-xxx-xx-xx.us-west-/users/auth/linkedin/callback |
Rails: how to use scope inside has_many block in Model Posted: 03 Dec 2016 12:54 AM PST In Rails 4 I am using: class Ticket < ActiveRecord::Base has_many :request_attendances, dependent: :destroy has_many :attending_request_attendances, -> { where("data->>'rsvp_completed' = 'true'") .where("data->>'is_coming' = 'true'") }, class_name: 'RequestAttendance' end In my Tickets model And class RequestAttendance < ActiveRecord::Base belongs_to :tickets, inverse_of: :request_attendances scope :is_coming, -> { where("data->>'is_coming' = 'true'")} scope :rsvp_completed, -> { where("data->>'rsvp_completed' = 'true'")} end In my RequestAttendance model I would like to do something like this has_many :attending_request_attendances, -> { :is_coming :rsvp_completed }, class_name: 'RequestAttendance' To reuse the scope I have created in my RequestAttendance model. Is something like this possible, at the moment it does not work, giving me the following error: undefined method `except' for :rsvp_completed:Symbol If I add a where to the has_many block like this: has_many :attending_request_attendances, -> { :is_coming :rsvp_completed where("data->>'rsvp_completed' = 'true'") }, class_name: 'RequestAttendance' It does not error, however it also does not use the scope clauses either. |
Query free time in appointment model Rails Postgres [on hold] Posted: 02 Dec 2016 08:01 PM PST I have an app that has Appointments which belong to Providers and I am looking to create a query that finds a provider's gaps in appointments Appointments are stored as a start and finish both which are datetimes . Ideally I would call Provider.free_appointment_slots(length,start,finish) where length is the length of the appointment required and start and finish are bounds of the search ie a particular week or day. I think it should be somewhat similar to this... How to return all the free periods of time from an appointment set or Finding free blocks of time in mysql and php? any help would be much appreciated |
How can I show Active Admin filters depending of controller params Posted: 02 Dec 2016 08:09 PM PST I need to do something like this: filter :name, if: proc { params[:foo] == 'bar' } Or even better do something like this: if params[:foo] == 'bar' filter :name end Probably it does not make any sense trying to access URL params outside a controller block. However to give you some context I have two index pages (like table and grid) and need to show some filters in the table one but not in the grid one. The way I can tell it's rendering one or the other is checking the as parameter. Any ideas? |
Capybara cannot detect element even though it is visible on page Posted: 02 Dec 2016 07:09 PM PST I am using Capybara to manually fill out a page, however I am running into an issue. When it tries to execute this line (I tried also setting visible to false): find(:css, "[value='Laundry In Building']", visible: true).set(true) It gets the following error: Unable to find css "[value='Laundry In Building']" This is confusing because I see the field in the browser when the test is running. Furthermore, when I output page.body , I get the following: <div class="listing-edit-cb-item"> <input class="cb" id="building_features_3" name="features[]"value="Laundry In Building" type="checkbox" /> <label for="building_features_3"> <span class="cb"></span> <span style="width: 200px; display: inline-block; font-size: 0.90em;">Laundry In Building</span> </label> </div> Why is Capybara no table to detect the checkbox element? |
undefined method `model_path' for #<#<Class:> UPDATE method Posted: 02 Dec 2016 07:43 PM PST I'am getting this error: undefined method `invite_path' for #<#<Class:0x9396d38>:0x8f8fb30> My controller class ConfirmationsController < ApplicationController skip_before_action :verify_authenticity_token def index @confirmation = Invite.joins(:user).select('invites.horario_desde, invites.horario_hasta, invites.estado, users.email, users.nombre, users.apellido, users.telefono, invites.complejo') .where(:hash_id => filter_params[:hash_id],:user_id => filter_params[:user_id]).first end (it gets only one record) My Routes get '/confirmations' => 'confirmations#index' post '/confirmations' => 'confirmations#update' And my view <%= form_for @confirmation do |confirmation|%> <p>Horario: de <%= confirmation.horario_desde %> a <%= confirmation.horario_hasta %></p> <p>Email: <%= confirmation.email %></p> <p>Teléfono: <%= confirmation.telefono %></p> <%=f.submit 'Confirm'%> <%=f.submit 'Cancel'%> <%end%> The idea is to show some data from my controller (@confirmations) and if the user clicks "confirm" should update my model with a particular status. But I'm not even able to make this form works. Is there another better way? Thanks |
No comments:
Post a Comment