Rails 5 include ActiveModel Select Method Posted: 16 Sep 2016 08:24 AM PDT https://github.com/emrahyildirim/radgroup/ /App/view_models/forms_model.rb class FormModel include ActiveModel::Model Rails console FormModel.select(:name) can not use the command. error nomethoderr (private method 'select' called for I am asking for your help. |
show result of js function in erb Posted: 16 Sep 2016 08:20 AM PDT I've got a js function which returns array function getArray(){ var array = []; $(".field").each(function() { array.push($(this).attr("id")); }) return array; } and I've got a button_tag <%= button_tag "heh",:type => "button", :onclick => "return getArray();" %> I need to get the result of getArray() function after clicking on button_tag and show it on the html page or console. |
How to implement a booking system in Rails? [on hold] Posted: 16 Sep 2016 08:23 AM PDT I'm new to Rails and I'm trying to develop a simple web application that allows students to make reservation for a washing machine in my college. I read many discussions about booking systems in Rails but I didn't find answer to my specific problem. My system should allow to book a washing machine only for the next seven days, time-slots are predetermined and for each there are 4 available washing machines. I build the model: - Student
- Washing machine
- Booking
I've already set validations e associations. My question is: Should I implement a background job which create "empty" bookings in the database? Other solutions? |
Why use Puma if we already have HTTP servers such as Nginx [duplicate] Posted: 16 Sep 2016 08:28 AM PDT This question already has an answer here: Why is it commonplace to use the next architecture? Client (e.g: browser) --> Nginx --> Puma --> Rails App I think that we can go without using Puma at all since it's also an HTTP server as Nginx with less capabilities. Having Puma in the middle, is having a second HTTP server, and we already have Nginx that handles HTTP requests. The only thing that Nginx would lack instead is a Rack interface to communicate with Rails, but that just a matter of implementing an Rack adapter for it. So instead we can have this and eliminate redundancy: Client (e.g: browser) --> Nginx --> Rails App Basically what am I missing here? Puma knows how to handle various Rails processes? If so, then Nginx can create several worker_processes also. Edit: Thanks to "meagar". I didn't know it was a duplicated post. I took a look at related posts but I couldn't find information. Very informative. |
Getting started with engines Posted: 16 Sep 2016 07:57 AM PDT I'm trying to generate an engine so I use $ rails plugin new dashboard --mountable,where dashboard is the name of the engine , it gives me this error /usr/local/bin/rails:23:in load': cannot load such file -- /var/lib/gems/2.3.0/gems/rails-5.0.0.1/bin/rails (LoadError) from /usr/local/bin/rails:23:in ' although this command worked with me before |
Which is the right way to pass nested parameters to a build method ? (Ruby on Rails 5) Posted: 16 Sep 2016 07:49 AM PDT I am building a very simple application managing users and keys. Keys are nested attributes of a user. I am inspired by RailsCast #196. The models are defined as: class User < ApplicationRecord #Validations --- #Relations has_many :keys, :dependent => :destroy accepts_nested_attributes_for :keys, :reject_if => :all_blank, :allow_destroy => true end class Key < ApplicationRecord #Validations --- #Relations belongs_to :user end The users controller includes strong parameters: def user_params params.require(:user).permit(:nom, :prenom, :section, :email, :password, keys_attributes: [:id, :secteur, :clef]) end And I wish to initialize 1 key for each new user (users controller): # GET /users/new def new @user = User.new key = @user.keys.build({secteur: "Tous", clef: "ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678"}) end I tried many ways to initialize the user's key, but I can't figure out how to pass parameters to it. User is always created, but the first key is not. No error message is issued. |
Rails / Stripe - undefined method `stripe_token' for nil:NilClass Posted: 16 Sep 2016 08:03 AM PDT I'm using Stripe for payments on my Rails app and I've hit the error above. I've recently moved a big chunk of my code from my controller to model and this is the first time I've hit this error (I've tested payments before and it never came up). Not really sure why this is coming up now. Here's my Model code - Booking.rb class Booking < ActiveRecord::Base belongs_to :event belongs_to :user def reserve # Don't process this booking if it isn't valid return unless valid? # We can always set this, even for free events because their price will be 0. self.total_amount = quantity.to_i * event.price_pennies.to_i # Free events don't need to do anything special if event.is_free? save # Paid events should charge the customer's card else begin charge = Stripe::Charge.create(amount: total_amount, currency: "gbp", card: @booking.stripe_token, description: "Booking number #{@booking.id}", items: [{quantity: @booking.quantity}]) self.stripe_charge_id = charge.id save rescue Stripe::CardError => e errors.add(:base, e.message) false end end end end And in my controller - bookings_controller.rb def create # actually process the booking @event = Event.find(params[:event_id]) @booking = @event.bookings.new(booking_params) @booking.user = current_user if @booking.reserve flash[:success] = "Your place on our event has been booked" redirect_to event_path(@event) else flash[:error] = "Booking unsuccessful" render "new" end end Here's the error message - I'm pretty new to Rails so apologies if this seems straightforward, any help would be appreciated. |
Rails many to many associations and has_many, through: Posted: 16 Sep 2016 08:25 AM PDT I created my models a week ago, but I didn't know many things that I know now so it is time to create it from scratch. What I want to accomplish is to create: - Lab model that can have many offers
Offer model that can have many labs. #MIGRATION FILES BELOW: class CreateLabs < ActiveRecord::Migration[5.0] def change create_table :labs do |t| t.string :name ... t.timestamps end end end class CreateOffers < ActiveRecord::Migration[5.0] def change create_table :offers do |t| t.string :name ... t.timestamps end end end # Join table: class CreateLabChain < ActiveRecord::Migration[5.0] def change create_table :lab_chain do |t| t.references :lab, foreign_key: true t.references :offer, foreign_key: true t.timestamps end end end
And here is how the model files look like: class Lab < ApplicationRecord has_many :offers, through: :lab_chain has_many :lab_chains end class Offer < ApplicationRecord has_many :labs, through: :lab_chain has_many :lab_chains end class LabChain < ApplicationRecord belongs_to :lab belongs_to :offer end I just want to know if I wrote it all correctly as I am not sure about all those tutorials I have watched and read. Bonus question is what if I want my Offer to have many sections, and section to have many offer_items? Should I just add: to Offer: has_many :sections has_many :offer_items, through: :section and then to Section: has_many :offer_items belongs_to :offer and the to OfferItem: belongs_to :section ? As I mentioned before, I volunteered as a guy that would make a website for our school project as I was the only one that had something to do with code (different language). It is harder than I thought. EDIT How would I also correctly add an self join in Section, so a section can have a subsection and so on? Self joins addded to Section model has_many :child_sections, class_name: "Section", foreign_key: "section_id" belongs_to :parent_section, class_name: "Section" Added to migration file t.references :parent_section, foreign_key: "section_id" |
binding.pry in Rails View: NameError: undefined local variable or method Posted: 16 Sep 2016 07:41 AM PDT I use Rails 4 with the gems byebug, pry-rails, pry-byebug, pry-stack_explorer. When i replace in a view file: <td class="subtotal"><%= order.display_item_total %></td> with <td class="subtotal"><%= binding.pry %></td> and type inside the console where the rails server process is running and the execution stopped at the pry breakpoint: order.inspect i get the error message: NameError: undefined local variable or method `order' for #<ActionView::OutputBuffer:0x007fdf13d99bb8> When i replace binding.pry with order.inspect i get the object info of order in the browser. I would expect that I should be able to get the object order inside the pry session in the console. What am I doing wrong? |
Rails: Create an inverse relationship between friends Posted: 16 Sep 2016 07:37 AM PDT I'm trying to build a facebook clone and finally got friends acceptance to work, but now I'm trying to have a bidirectional relationship between the two friends. friendship.rb class Friendship < ApplicationRecord #after_create :create_inverse_relationship after_destroy :destroy_inverse_relationship belongs_to :user belongs_to :friend, class_name: "User" def create_inverse_relationship #byebug friend.friendships.build(friend_id: current_user.id) end def destroy_inverse_relationship friendship = friend.friendship.find_by(friend: user) friendship.destroy if friendship end end When a user accepts a friend request I get an error in my create_inverse_relationships method saying: undefined method `friendships' for nil:NilClass friend_request.rb class FriendRequest < ApplicationRecord belongs_to :user belongs_to :friend, class_name: 'User' def accept user.friends << friend Friendship.new.create_inverse_relationship end def destroy end end user.rb class User < ApplicationRecord has_many :friend_requests, dependent: :destroy has_many :pending_friends, through: :friend_requests, source: :friend has_many :friendships, dependent: :destroy has_many :friends, through: :friendships # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable end friend_request_controller.rb class FriendRequestsController < ApplicationController before_action :set_friend_request, except: [:index, :create] def index @incoming = FriendRequest.where(friend: current_user) @outgoing = current_user.friend_requests end def create @user = User.find(current_user) friend = User.find(params[:friend_id]) @friend_request = current_user.friend_requests.new(friend_id: friend.id) if @friend_request.save redirect_to user_path(current_user) end end def update friend = User.find(params[:friend_id]) @friend_request = current_user.friend_requests.find_by(friend_id: friend.id) @friend_request.accept end def destroy @friend_request.destroy end private def set_friend_request @friend_request = FriendRequest.find(params[:id]) end end Any guidance would be greatly appreciated |
Rails - Delete a specific item only if the checkbox is checked Posted: 16 Sep 2016 07:55 AM PDT I am trying to delete a tweet from my model only if the checkbox aside is checked. Here is a screenshot: Here is the beginning of the code in my view: <% @twits.each do |twit| %> <li> <%= link_to "#{twit.link}", twit_path(twit) %> | Engagement => <%= twit.engagement %> | <%= twit.like %> likes | <%= twit.retweet %> retweets | on <%= twit.first_date %> <%= check_box_tag("delete[#{twit.id}]",1) %> - <%= link_to twit_path(twit) do %> <i class="glyphicon glyphicon-eye-open"></i> <% end %> - <%= link_to twit_path(twit), method: :delete do %> <i class="glyphicon glyphicon-trash"></i> <% end %> </li> <% end %> EDIT => Here is my controller destroy action, very basic. def destroy @twit.destroy redirect_to twits_path end Thanks for your help! |
Versioning rails API Posted: 16 Sep 2016 07:30 AM PDT I was trying to find a way to manage different versions for my rails API. Different routing is not a problem, the problem begins when i'm changing the models and the database (Postgres) between different versions. What is the best practice for managing different versions in rails API ? Thanks guys |
Rails 5 API Strong Parameters behavior Posted: 16 Sep 2016 07:26 AM PDT I generated a new rails 5 --api --database=postgresql app the other day and only created one scaffold (Hero). I'm wondering how the strong parameters work in rails as I am seeing some odd behavior: Controller looks like: def create hero = Hero.new(hero_params) if hero.save render json: hero, status: :created, location: hero else render json: hero.errors, status: :unprocessable_entity end end My hero_params look like this: def hero_params params.require(:hero).permit(:name) end So I would assume that the client is required to submit a hash containing a "hero" key and it's allowed to have a "name " subkey that is allowed to be mass assigned when this controller action is called. Meaning, the JSON should look like this: { "hero": { "name": "test" } } All is well but here is where I am seeing strange behavior. When the user submits the exact JSON as above, the parameters come in as: Parameters: {"hero"=>{"name"=>"test"}} Now if the user submits just: { "name": "test" } It still creates a new resource and the parameters come in as: Parameters: {"name"=>"test", "hero"=>{"name"=>"test"}} Why are there two sets of parameters, one with the actual submitted data and one in the format of a hero object as if it was anticipating the mass assignment? How come the require(:hero) doesn't raise an error when that key is not submitted? I assume the answer to this is because of what is automatically creating that second hash ("hero"=>{"name"=>"test"}} from question 1. Any information on what I am missing here would be greatly appreciated, as this is barebones rails behavior out-of-the-box. |
ActionCable not updating page Posted: 16 Sep 2016 06:56 AM PDT I'm creating a ruby app, and I'm trying to implement action cable, when a user makes a post, I want the post index to update for all users. In my channels/posts.js i have: App.posts = App.cable.subscriptions.create("PostsChannel", { connected: function() { // Called when the subscription is ready for use on the server }, disconnected: function() { // Called when the subscription has been terminated by the server }, received: function(data) { // Called when there's incoming data on the websocket for this channel console.log(data) $('#list').html("<%= escape_javascript render('list') %>") } }); in PostRelayJob.rb I have: class PostRelayJob < ApplicationJob queue_as :default def perform(post) ActionCable.server.broadcast "posts", post: PostsController.render(list) # Do something later end end and in models/post.rb: after_commit { PostRelayJob.perform_later(self) } When I add a post in the server console I get: [ActiveJob] [PostRelayJob] [57126ec7-b091-48fc-91aa-2f940caa9421] Performing PostRelayJob from Async(default) with arguments: #<GlobalID:0x00000003aa10d8 @uri=#<URI::GID gid://today-i-have2/Post/15>> [ActiveJob] Enqueued PostRelayJob (Job ID: 57126ec7-b091-48fc-91aa-2f940caa9421) to Async(default) with arguments: #<GlobalID:0x000000037af000 @uri=#<URI::GID gid://today-i-have2/Post/15>> [ActiveJob] [PostRelayJob] [57126ec7-b091-48fc-91aa-2f940caa9421] Performed PostRelayJob from Async(default) in 3.66ms Rendering posts/create.js.erb Rendered posts/_list.html.erb (7.5ms) Rendered posts/create.js.erb (9.0ms) However the post in the other browser doesn't update, I'm pretty new to rails so any help would be greatly appreciated. |
Redmine to Easyredmine, Rails Posted: 16 Sep 2016 06:40 AM PDT I'm trying to upgrade from redmine to easyRedmine following this doc: https://www.easyredmine.com/resources/installation/234-redmine-upgrade-to-easy I get an error while migrating plugins, the error is : ActionView::Template::Error (The single-table inheritance mechanism failed to locate the subclass: 'ContactCustomField'. This error is raised because the column 'type' is reserved for storing the class in case of inheritance. Please rename this column if you didn't intend it to be used for storing the inheritance class or overwrite EasyPageModule.inheritance_column to use another column for that information.) I found this : https://www.easyredmine.com/knowledge-base?view=knowledge_detail&id=166&category_id=64#maincol It's true that i've deleted the plugins files directly, i reinstalled them again and i uninstalled them right, and still have the problem. However on the link i provided there is the part of editing from the rails console, but i've no idea how to do that, any one can help? |
Loop through block in rails helper Posted: 16 Sep 2016 06:49 AM PDT I'm trying to create a Rails helper that takes a block and loops through that to produce: <span data-param1="param1" data-param2="param2"> <span data-options="test"> <span data-options="test"> </span> An example of the helper in use: <%= main(param1, param2) do %> <%= sub('param', :options => 'test') %> <%= sub('param', 'test') %> <% end %> And then the helper itself: module MyHelper def main(param1, param2, &block) raise ArgumentError.new('Missing block!') unless block_given? content_tag :span, :data => { :param1 => param1, :picture => '' } do markup = content_tag(:span, '', :data => { :param2 => param2 }).to_s #loop through blocks of subs &block.each do |item| sub = sub(item.param, item.options) data = { :param => param } data[:options] = sub.options unless sub.options.blank? markup << content_tag(:span, '', :data => data).to_s end markup end private def sub(param, options = {}) options = extract_options!(options) end # returns a string def extract_options!(options) when String options when Hash #removed for this question else raise ArgumentError.new('Only Hash && String allowed!') end end Note: I've removed the Hash handling in the extract_options to keep the question code short. However it doesn't like the &block loop and gives this error: syntax error, unexpected &, expecting keyword_end &block.each do |item| ^ |
How to create new record via has_many through by Rails? Posted: 16 Sep 2016 06:10 AM PDT I am currently struggling with a has_many :through association in my project. This is my model class Group < ActiveRecord::Base has_many :user_groups ,dependent: :destroy has_many :users , through: :user_groups end class User < ActiveRecord::Base has_many :user_groups ,dependent: :destroy has_many :groups , through: :user_groups end class UserGroup < ActiveRecord::Base belongs_to :user , inverse_of: :placements belongs_to :group , inverse_of: :placements validates :level , presence: true end So when i tried to create new group but it didn't work out. This is my controller class GroupController < ApplicationController def create group = Group.new(group_params) group.users << User.find_by(id: current_user.id) if group.save render json: group, status: 201, location: [group] else render json: { errors: group.errors }, status: 422 end end private def group_params params.require(:group).permit(:name, :shuttle_price, :court_price) end end But when i call create method i got this error. Could not find the inverse association for group (:placements in Group) On this line group.users << User.find_by(id: 6) So how can i fix this? Thanks! |
Rails5 - best type for storing hours and minutes Posted: 16 Sep 2016 06:52 AM PDT What type should I assign to a variable to store opening and closing time of a place? Should it be datetime, time or just a simple string? Which one is easier to manage? |
How to validatie date picker that stat date and time must be greater than current date and time? Posted: 16 Sep 2016 05:27 AM PDT How can I validate my rails app form validation on date picker that stat date and time must be greater than current date and time? I'm using jQuery in my rails app. This is my js code $("#datetimepicker_start").on("dp.change", function (e) { var date = $("#datetimepicker_start").find("input").val(); var end_time = new Date(e.date); var end_min_time = end_time.getHours() + 4; // var minutes = end_time.getMinutes() - 1; var setThis = moment(end_time.setHours(end_min_time)); // var setThis = moment(end_time.setMinutes(minutes)); $('#datetimepicker_end').data("DateTimePicker").viewDate(setThis); }); $("#datetimepicker_end").on("dp.change", function (e) { $('#datetimepicker_start').data("DateTimePicker").maxDate(e.date); }); $('#datetimepicker_end_recur_date').datetimepicker({ format : 'MM/DD/YYYY', minDate : 'now', // minDate : moment(), widgetPositioning: { horizontal: 'right', vertical: 'bottom' }, icons : { time : "fa fa-clock-o", date : "fa fa-calendar", up : "fa fa-arrow-up", down : "fa fa-arrow-down", right : "fa fa-arrow-right", left : "fa fa-arrow-left" } }); |
Rails - how to set default values in a model for quantity Posted: 16 Sep 2016 05:16 AM PDT I'm trying to allow a User to book events for more than one space at a time, so if one space at an event costs £10 and a User wants to book four spaces then they would need to pay £40. I've implemented a method in my Booking model to cater for this - Booking.rb class Booking < ActiveRecord::Base belongs_to :event belongs_to :user def reserve # Don't process this booking if it isn't valid return unless valid? # We can always set this, even for free events because their price will be 0. self.total_amount = quantity * event.price_pennies # Free events don't need to do anything special if event.is_free? save # Paid events should charge the customer's card else begin charge = Stripe::Charge.create(amount: total_amount, currency: "gbp", card: @booking.stripe_token, description: "Booking number #{@booking.id}", items: [{quantity: @booking.quantity}]) self.stripe_charge_id = charge.id save rescue Stripe::CardError => e errors.add(:base, e.message) false end end end end When I try to process a booking I get the following error - NoMethodError in BookingsController#create undefined method `*' for nil:NilClass This line of code is being highlighted - self.total_amount = quantity * event.price_pennies I need to check/make sure that quantity returns a value of 1 or more and event.price_pennies returns 0 if it is a free event and greater than 0 if it is a paid event. How do I do this? I did not set any default values for quantity in my migrations. My schema.rb file shows this for price_pennies - t.integer "price_pennies", default: 0, null: false This is whats in my controller for create - bookings_controller.rb def create # actually process the booking @event = Event.find(params[:event_id]) @booking = @event.bookings.new(booking_params) @booking.user = current_user if @booking.reserve flash[:success] = "Your place on our event has been booked" redirect_to event_path(@event) else flash[:error] = "Booking unsuccessful" render "new" end end So, do I need a method in my booking model to rectify this or should I do a validation for quantity and a before_save callback for event? I'm not quite sure how to do this so any assistance would be appreciated. |
Configure Websocket-rails on production with nginx and SSL Posted: 16 Sep 2016 04:46 AM PDT Installed and configured Websocket-rails gem on local environment with the following configuration: WebsocketRails.setup do |config| config.standalone = false config.synchronize = true end Controller: WebsocketRails["channel"].trigger 'new', 'some data' Javascript: var dispatcher = new WebSocketRails(document.location.host + '/websocket', false); var channel = dispatcher.subscribe("channel"); channel.bind('new', function (data) { console.log(data); }); All this works fine on local environment. After deploying it on staging server where we have configured SSL. Got the following error: Mixed Content: The page at 'https://staging.example.com' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://staging.example.com/websocket'. This request has been blocked; the content must be served over HTTPS. XMLHttpRequest cannot load http://staging.example.com/websocket. Failed to start loading. Ngnix Configuration: server { location /websocket { proxy_pass https://staging.example.com/websocket; proxy_http_version 1.1; proxy_set_header Upgrade websocket; proxy_set_header Connection Upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } Am I missing something in the configuration? |
hash inside liste of hash extracted from array Posted: 16 Sep 2016 06:31 AM PDT I have a simple array arr = ["Japan", "Egypt", "Spain", "Brazil",....] I want to extract each element and make it a hash japan = Hash.new("Japan") egypt = Hash.new("Egypt") brazil = Hash.new("Brazil") finally store all of the hash inside a groupping hash country = {"Japan" => 0, "Egypt" => 0,"Brazil" => 0,.....} |
string interpolation in devise flash messages? Posted: 16 Sep 2016 04:36 AM PDT I'm new to RoR and I would like to personalise the Devise flash messages to use the name of the current user. I've seen that the original file includes the following line: devise.en.yml failure: "Could not authenticate you from %{kind} because \"%{reason}\"." So I've applied the same rule to: sessions: signed_in: "Welcome back!." signed_out: "See you soon!." - sessions: signed_in: "Welcome back! \"#{current_user.first_name}\"." signed_out: "See you soon! \"#{current_user.first_name}\"." but the code is not executing, and prints the whole sentence as string. Any help would be appreciated! :) |
Can't connect http://localhost:3000/ Ruby On Rails Posted: 16 Sep 2016 04:54 AM PDT I'm following a Youtube tutorial and could open http://localhost:3000/ in the beginning. Youtube tutorial name: "Your First Rails Application [ Ruby on Rails from the ground up - 4/5 ]" But now, 15 mins in, I can't open http://localhost:3000/ anymore. Why? What information do you need from me, to be able to answer this questions? I searched for an answer, but couldn't find any answer that made sense to me. Only answers about "0.0.0.0". Thank you. Jonas |
Rubocop JSON: Align the parameters of a method call if they span more than one line Posted: 16 Sep 2016 04:35 AM PDT i got a problem with Rubocop in my testing files. At first, this is my code now: should 'should show user' do get user_url(@user), headers: @header assert_response :success end should 'should update user' do patch user_url(@user), params: { data: { attributes: { name: @user.name } } }, headers: @header assert_response :success end And that is the Rubocop error output: test/controllers/users_controller_test.rb:34:9: C: Align the parameters of a method call if they span more than one line. headers: @header ^^^^^^^^^^^^^^^^ test/controllers/users_controller_test.rb:40:9: C: Align the parameters of a method call if they span more than one line. params: { ... ^^^^^^^^^ So I searched in the styleguide for the correct alignment of JSON. I really tried every combination of indenting and new lines, but Rubocop throws every time the same error. Andy by the way, put the whole JSON in one line is also not the solution. Can anybody explain, how the correct alignment looks like, so that Rubocop is happy with it? |
Is there anyway to know how many requests got dropped by Apache/Rails? Posted: 16 Sep 2016 04:11 AM PDT We've an ecommerce store (Rails 3.2, Phusion Passenger on Apache) which gets lot of traffic at certain peak hours. We want to ensure that no users are closing the tab, losing patience due to a longer response time from server. Is there anyway to know if a user didn't wait for the request to finish loading? Maybe Apache/Rails drops the request when user runs away? Can we know how many requests are getting dropped and correlate it with server load? Also when I find a way to measure that, we'd also like to know how many concurrent users are using my website at that time. Any insights? |
ActiveRecord::InvalidForeignKey in Admin::UsersController#destroy Posted: 16 Sep 2016 08:26 AM PDT In ActiveAdmin, when I want to delete a user I have the following error : ActiveRecord::InvalidForeignKey in Admin::UsersController#destroy PG::ForeignKeyViolation: ERROR: update or delete on table "users" violates foreign key constraint "fk_rails_b080fb4855" on table "notifications" DETAIL: Key (id)=(15) is still referenced from table "notifications". : DELETE FROM "users" WHERE "users"."id" = $1 I already have has_many :notifications, dependent: :destroy in my User model so I don't understand the error. Notification model: class Notification < ActiveRecord::Base before_validation :check_modeles validates :message, presence: true validates :modele, presence: true validates :user_id, presence: true validates :contact_id, presence: true validates_associated :user belongs_to :user belongs_to :contact, :class_name => "User", :foreign_key => "contact_id" User model : class User < ActiveRecord::Base before_validation :check_genres before_validation :set_image before_validation :init_attrs before_create :set_name before_create :create_mangopay after_create :set_centres_interets after_create :set_preferences_musicales after_create :check_on_create after_update :check_on_update before_update :create_mangopay_bank_account before_destroy :remove_contact_notifications acts_as_mappable :default_units => :kms, :lat_column_name => :last_lat, :lng_column_name => :last_lng devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable has_one :fil, dependent: :destroy has_one :preferences_voyage, dependent: :destroy has_one :verification, dependent: :destroy has_many :badges, dependent: :destroy has_many :favoris , dependent: :destroy has_many :centres_interets, dependent: :destroy has_many :preferences_musicales, dependent: :destroy has_many :recommandations, dependent: :destroy has_many :reputations, dependent: :destroy has_many :reservations, dependent: :destroy has_many :routes, dependent: :destroy has_many :trajets_reguliers, dependent: :destroy has_many :vehicules, dependent: :destroy has_many :contact_notifications, foreign_key: 'contact_id', class_name: 'Notification', dependent: :destroy has_many :notifications, dependent: :destroy has_many :recherches, dependent: :destroy has_many :blocages, dependent: :destroy has_many :messageries, dependent: :destroy has_many :messages, dependent: :destroy validates :date_naissance, presence: true validates :first_name, presence: true validates :last_name, presence: true Maybe the has_many :notifications, dependent: :destroy only affect the user and not the contact? If so, how do i fix it? |
Doorkeeper not working after an upgrade from 1.4 to 4.0, not sure what to try next Posted: 16 Sep 2016 06:30 AM PDT I upgraded a rails app using Doorkeeper from rails 4.0 to 4.2 It also updated Doorkeeper to 4.0 from 1.4 The doorkeper app use Devise to authenticate user. When allowing a client to use doorkeeper, the user is correctly redirected on the doorkeeper/provider app, and can log. User is immediately redirected on the third party app. But when the Third Party app contact directly the API of the doorkeeper provider app, the answer is a 403 with the following error in the logs : Filter chain halted as :doorkeeper_authorize! rendered or redirected I tried to identify a problem by comparing the doorkeeper app with examples from doorkeeper but it seems it should work. I have no idea what to do next to solve my problem. EDIT: I followed panda advice and i added scopes to doorkeeper_authorize! : before_action -> { doorkeeper_authorize! :public,:user,:admin } Now everything works like in the previous version. |
sqlite3 load error while start rails5 server Posted: 16 Sep 2016 06:13 AM PDT I'v install ruby version 2.3.1p112 with ruby devkit on windows 10 64bit using ruby installer and rails 5 then run command: rails new app I'v got my new app directory then I cd in it then run bundle install rails s but I'v got this error: LoadError (Could not load 'active_record/connection_adapters/sqlite3_adapter'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.): I'v edit sqlite3-1.3.11-x86-mingw32.gemspec file in line 10 from this: s.require_paths = ["lib"] to this: s.require_paths = ["lib/sqlite3_native"] but the same error appear. datebase.yml : # SQLite version 3.x # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem 'sqlite3' # default: &default adapter: sqlite3 pool: 5 timeout: 5000 development: <<: *default database: db/development.sqlite3 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: <<: *default database: db/test.sqlite3 production: <<: *default database: db/production.sqlite3 This is my Gemfile : source 'https://rubygems.org' # Use credit_debit_card_number_validator to validate and generate card numbers gem 'credit_debit_card_number_validator' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 5.0.0', '>= 5.0.0.1' # Use Puma as the app server gem 'puma', '~> 3.0' # Use SCSS for stylesheets gem 'sass-rails', '~> 5.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .coffee assets and views gem 'coffee-rails', '~> 4.2' # See https://github.com/rails/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks gem 'turbolinks', '~> 5' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.5' # Use Redis adapter to run Action Cable in production # gem 'redis', '~> 3.0' # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development group :development, :test do # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug', platform: :mri # Use sqlite3 as the database for Active Record gem 'sqlite3' end group :development do # Access an IRB console on exception pages or by using <%= console %> anywhere in the code. gem 'web-console' end # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] and this is Application trace : This error occurred while loading the following files: active_record/base finally this is Framework trace : activesupport (5.0.0.1) lib/active_support/dependencies.rb:293:in `require' activesupport (5.0.0.1) lib/active_support/dependencies.rb:293:in `block in require' activesupport (5.0.0.1) lib/active_support/dependencies.rb:259:in `load_dependency' activesupport (5.0.0.1) lib/active_support/dependencies.rb:293:in `require' activerecord (5.0.0.1) lib/active_record/connection_adapters/sqlite3_adapter.rb:8:in `<top (required)>' activesupport (5.0.0.1) lib/active_support/dependencies.rb:293:in `require' activesupport (5.0.0.1) lib/active_support/dependencies.rb:293:in `block in require' activesupport (5.0.0.1) lib/active_support/dependencies.rb:259:in `load_dependency' activesupport (5.0.0.1) lib/active_support/dependencies.rb:293:in `require' activerecord (5.0.0.1) lib/active_record/connection_adapters/connection_specification.rb:174:in `spec' activerecord (5.0.0.1) lib/active_record/connection_handling.rb:53:in `establish_connection' activerecord (5.0.0.1) lib/active_record/railtie.rb:125:in `block (2 levels) in <class:Railtie>' activesupport (5.0.0.1) lib/active_support/lazy_load_hooks.rb:38:in `instance_eval' activesupport (5.0.0.1) lib/active_support/lazy_load_hooks.rb:38:in `execute_hook' activesupport (5.0.0.1) lib/active_support/lazy_load_hooks.rb:45:in `block in run_load_hooks' activesupport (5.0.0.1) lib/active_support/lazy_load_hooks.rb:44:in `each' activesupport (5.0.0.1) lib/active_support/lazy_load_hooks.rb:44:in `run_load_hooks' activerecord (5.0.0.1) lib/active_record/base.rb:324:in `<module:ActiveRecord>' activerecord (5.0.0.1) lib/active_record/base.rb:24:in `<top (required)>' activesupport (5.0.0.1) lib/active_support/dependencies.rb:293:in `require' activesupport (5.0.0.1) lib/active_support/dependencies.rb:293:in `block in require' activesupport (5.0.0.1) lib/active_support/dependencies.rb:259:in `load_dependency' activesupport (5.0.0.1) lib/active_support/dependencies.rb:293:in `require' activerecord (5.0.0.1) lib/active_record/migration.rb:558:in `connection' activerecord (5.0.0.1) lib/active_record/migration.rb:545: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.3.1) lib/web_console/middleware.rb:131:in `call_app' web-console (3.3.1) lib/web_console/middleware.rb:28:in `block in call' web-console (3.3.1) lib/web_console/middleware.rb:18:in `catch' web-console (3.3.1) 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' |
form for reviewing user Posted: 16 Sep 2016 04:09 AM PDT Hi i m a newbie and i am currently branching out from Hartl's tutorial. I would like to implement a user review. I have no problem doing it inside rails console but i am having trouble with the forms. Thank you so much in advance. The form is able to save but doesnt save the content. INSERT INTO "reviews" ("reviewer_id", "reviewee_id", "created_at","updated_at") VALUES ($1, $2, $3, $4) RETURNING "id" [["reviewer_id", 1], ["reviewee_id", 15], ["created_at", 2016-09-16 09:52:49 UTC], ["updated_at", 2016-09-16 09:52:49 UTC]] User model: has_many :active_reviews, class_name: "Review", foreign_key:"reviewer_id", dependent: :destroy has_many :passive_reviews, class_name: "Review", foreign_key:"reviewee_id", dependent: :destroy has_many :reviewing, through: :active_reviews, source: :reviewee has_many :reviewers, through: :passive_reviews, source: :reviewer def review(other_user, great) active_reviews.create!(reviewee_id: other_user.id, content: great) end Review model: belongs_to :reviewer, class_name: "User" belongs_to :reviewee, class_name: "User" validates :reviewer_id, presence: true validates :reviewee_id, presence: true Review controller: class ReviewsController < ApplicationController before_action :logged_in_user, only: [:create, :destroy] def create @review = current_user.active_reviews.build @user = User.find(params[:reviewee_id]) current_user.review(@user, :content) redirect_to reviews_user_path(@user) flash[:success] = "User reviewed" end def destroy end end Views (shared/_review_form.html.erb) <%= form_for(@review) do |f| %> <%= render 'shared/error_messages', object: f.object %> <div><%= hidden_field_tag :reviewee_id, @user.id %></div> <%= f.text_area :content, placeholder: "Leave a review..." %> <%= f.submit "Submit", class: "btn btn-primary" %> <% end %> Views (users/user_reviews.html.erb) <% provide(:title, @title) %> <div class="row"> <aside class="col-md-4"> <section class="user_info"> <%= gravatar_for @user %> <h1><%= @user.name %></h1> <span><%= link_to "view my profile", @user %></span> <span><b>Microposts:</b> <%= @user.microposts.count %></span> </section> <section class="user_info"> <%= render 'shared/review_form' %> </section> <% @reviews.each do |r| %> <ol class="users follow"> <li><%= r.reviewer.name %>: <%= r.content %></li> </ol> <% end %> </aside> </div> |
No comments:
Post a Comment