Rails has_and_belongs_to_many association not working Posted: 04 Sep 2016 08:09 AM PDT I am trying to implement has_and_belongs_to_many in my project. The problem is that I am unable to insert data in join table that I have created to set to insert the entries in 3rd table. Here is my wine model: class Wine < ActiveRecord::Base has_and_belongs_to_many :restaurants, join_table: 'restaurants_wines' end Here is my restaurant model: class Restaurant < ActiveRecord::Base has_and_belongs_to_many :wines, join_table: 'restaurants_wines' end here is my restaurant form: <%= form_for([:admin, @current_object]) do |f| %> <div class='field'> <%= f.label :title -%> <%= f.text_field :title, :class => 'larger widest' -%> </div> <%= f.label :wines %> <%= f.select :id, Wine.all.collect { |p| [ p.title, p.id ] }, {}, { :multiple => true } %> <%= f.submit %> <% end %> Here is my Restaurant controller : I am permitting params as well: `params.require("#{model_name}".to_sym).permit(:title, :description, :lat, :lng, :address, :avatars, :wine_ids => [])` Here is my migration: class CreateRestaurantsWinesJoin < ActiveRecord::Migration def change create_table :restaurants_wines, id: false do |t| t.integer 'wine_id' t.integer 'restaurant_id' end add_index :restaurants_wines, %w(wine_id restaurant_id) end end What I really need to do is to pass ids to join table, I am not certain which step I am really missing here. If anyone could, please explain in detail as well with detailed answer. Thanks. |
Rails Differentiating dynamically added nested form has_many associations Posted: 04 Sep 2016 07:34 AM PDT I have a nested form that dynamically adds associations but my problem is that depending on which checkbox is clicked, a different div field will be displayed. To do this, I wrote some javascript to check the id's of the checkboxes and the fields to display. Problem: When there's more than one association, certain fields won't be displayed. I need a way to differentiate the id's of the checkboxes for each association. (They are currently all the same, e.g. task 1, task 2 etc. This is my main form partial: <%= form_for(@reservation) do |f| %> <% if @reservation.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@reservation.errors.count, "error") %> prohibited this reservation from being saved:</h2> <ul> <% @reservation.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <%= f.fields_for :customer_reservation do |f| %> <% if params[:customer_id] %> <%= f.hidden_field :customer_id, :value => @cust_id %> <% end %> <% end %> <%= f.fields_for :service_type_reservations do |f| %> <%= render 'service_type_reservation_fields', f: f %> <% end %> <%= link_to_add_fields 'Add service reservation', f, :service_type_reservations %> <!-- Find every element with the name attribute set to "new_record" and replace it with a timestamp. Now they won't have the same id --> <script type="text/javascript"> $('[data-form-prepend]').click( function(e) { var obj = $( $(this).attr('data-form-prepend') ); obj.find('input, select, textarea').each( function() { $(this).attr( 'name', function() { return $(this).attr('name').replace( 'new_record', (new Date()).getTime() ); }); }); obj.insertBefore( this ); return false; }); </script> <div class="actions"> <%= f.submit %> </div> <% end %> This is my association partial view: <div class="field"> <%= f.label :services %><br> <%= f.collection_radio_buttons :service_type_id, Booking::ServiceType.all, :id, :name, checked: params[:service_type_id] do |b| %> <div class="collection-radio-button" id="<%= Booking::ServiceType.find(b.value).id %>"> <%= b.radio_button %> <%= b.label %> </div> <% end %> </div> <div class="field" id="check_in_field" style="display:none;"> <%= f.label :check_in %><br> <%= f.datetime_select :check_in %> </div> <div class="field" id="check_out_field" style="display:none;"> <%= f.label :check_out %><br> <%= f.datetime_select :check_out %> </div> <div class="field" id="sel_date_field" style="display:none;"> <%= f.label :date %><br> <%= f.datetime_select :date %> </div> <div class="field" id="occupancy_field"> <%= f.label :persons %><br> <%= f.number_field :occupancy %> </div> <% if f.object.persisted? %> <%= f.check_box :_destroy %> <%= f.label :_destroy, "Destroy" %> <% end %> <script type="text/javascript"> var checkedButton; var radioButtons = []; <% @serviceTypes.each do |service| %> var radioButton = document.getElementById('<%= service.id %>'); radioButtons.push(radioButton); <% end %> for(var index in radioButtons){ (function(){ radioButtons[index].addEventListener("change", onCheckClick.bind(radioButtons[index], index)); })(); } var check_in_field = document.getElementById('check_in_field'); var check_out_field = document.getElementById('check_out_field'); var date_sel_field = document.getElementById('sel_date_field'); var persons_field = document.getElementById('occupancy_field'); //If a service is selected in the beginning <% if @selectedService %> <% if @selectedService.multiple_day %> if (check_in_field){ check_in_field.style['display'] = 'block'; } if (check_out_field){ check_out_field.style['display'] = 'block'; } if (date_sel_field){ date_sel_field.style['display'] = 'none'; } <% elsif !@selectedService.multiple_day %> if (check_in_field){ check_in_field.style['display'] = 'none'; } if (check_out_field){ check_out_field.style['display'] = 'none'; } if (date_sel_field){ date_sel_field.style['display'] = 'block'; } <% end %> <% end %> function onCheckClick(index, radioButtonClicked){ <% @serviceTypes.each do |service| %> if(radioButtonClicked.target.value == <%= service.id %> && <%= service.multiple_day %>){ if (check_in_field){ check_in_field.style['display'] = 'block'; } if (check_out_field){ check_out_field.style['display'] = 'block'; } if (date_sel_field){ date_sel_field.style['display'] = 'none'; } }else if(radioButtonClicked.target.value == <%= service.id %> && <%= !service.multiple_day %>){ if (check_in_field){ check_in_field.style['display'] = 'none'; } if (check_out_field){ check_out_field.style['display'] = 'none'; } if (date_sel_field){ date_sel_field.style['display'] = 'block'; } } <% end %> }; </script> This is the application helper which has the link_to_add_fields function (taken from itay grudev's tutorial here --> ruby-on-rails-nested-attributes-tutorial module ApplicationHelper def link_to_add_fields(name = nil, f = nil, association = nil, options = nil, html_options = nil, &block) # If a block is provided there is no name attribute and the arguments are # shifted with one position to the left. # This re-assigns those values. f, association, options, html_options = name, f, association, options if block_given? options = {} if options.nil? html_options = {} if html_options.nil? if options.include? :locals locals = options[:locals] else locals = { } end if options.include? :partial partial = options[:partial] else partial = association.to_s.singularize + '_fields' end # Render the form fields from a file with the association name provided new_object = f.object.class.reflect_on_association(association).klass.new fields = f.fields_for(association, new_object, child_index: 'new_record') do |builder| render(partial, locals.merge!( f: builder)) end # The rendered fields are sent with the link within the data-form-prepend attr html_options['data-form-prepend'] = raw CGI::escapeHTML( fields ) html_options['href'] = '#' content_tag(:a, name, html_options, &block) end end Everytime I click the "add service reservation" button, a new service reservation is created but the fields besides the checkboxes and occupancy has "display:none", so I need a way to differentiate the new service reservations. Any help would be appreciated. Thanks! |
How to rake db:migrate on a Heroku staging pipeline? Posted: 04 Sep 2016 07:51 AM PDT I've setup an app on Heroku, and I've now also set up a pipeline for staging. I did this by creating a fork of my production app on Heroku, then adding this to the app pipeline under the "staging" stage. Before this (when I only had the app in production), I pushed updates to heroku from the CLI with git push heroku master . I could then update the database for new features with heroku run rake db:migrate . However, I'm not sure how you would do this with a staging app in a pipeline? I tried using the --remote appendage but it doesn't recognise the app (I think because the --remote was pre pipelines?) I have auto updates from git setup so that my app-staging always mirrors my git master, and I've just added a new feature which includes a table. The view on the staging site is now returning an error as I haven't run heroku run rake db:migrate on the staging site. I obviously don't want to push these changes to production without know this new feature works. So how do you do it? Any ideas how to rake db:migrate the pipeline staging database? I can't find any guidance in the heroku manual either :/ |
Google oauth error Posted: 04 Sep 2016 07:25 AM PDT I want to add oauth functionality to my work and I have installed the needed gems. Twitter and Facebook oauth are working perfectly. As for google, I got this error: JWT::ExpiredSignature Signature has expired When I reloaded the page, I got a different error: OAuth2::Error invalid_grant: Code was already redeemed. { "error" : "invalid_grant", "error_description" : "Code was already redeemed." } This is my omniauth.rb code require 'certified' Rails.application.config.middleware.use OmniAuth::Builder do provider :twitter, 'TWITTER_KEY','TWITTER_SECRET' provider :facebook, 'FACEBOOK_KEY', 'FACEBOOK_SECRET', scope: 'public_profile', info_fields: 'id,name,link' provider :google_oauth2, "GOOGLE_KEY", "GOOGLE_SECRET", scope: 'profile', image_aspect_ratio: 'square', image_size: 48, access_type: 'online', name: 'google' end This is my user model: class User < ActiveRecord::Base class << self def from_omniauth(auth_hash) user = find_or_create_by(uid: auth_hash['uid'], provider: auth_hash['provider']) user.name = auth_hash['info']['name'] user.location = auth_hash['info']['location'] user.image_url = auth_hash['info']['image'] user.url = auth_hash['info']['urls'][user.provider.capitalize] user.save! user end end end Any idea on how the errors can be solved??? |
Dynamic bootstrap modals in Rails application not working Posted: 04 Sep 2016 08:11 AM PDT I'm creating a simple app and I'm trying to add dynamically generated modals like this: <% @friends.each do |friend| %> <div class = "row user"> <div class = "col-sm-4" > <img class="friend-picture" src=" <%= friend["image"][2]["content"] %> "> </div> <div class = "col-sm-4"> <h4 class="user-name text-center"><%= friend["name"] %> </h4> <ul class="list-group"> <% @lastfm.getFriendTracks(friend["name"]).each do |track| %> <li class="list-group-item"> <%= track["artist"]["content"] %> - <%= track["name"] %> <br> <div class="text-right comments"> <a type="button" data-toggle="modal" data-target="#comments_<%=track["artist"]["content"]%>_<%=track["name"]%>">3 comments</a> </div> <div id="comments_<%=track["artist"]["content"]%>_<%=track["name"]%>" class = "modal fade" role = "dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title"> <%= track["artist"]["content"] %> - <%= track["name"] %> </h4> </div> <div class="modal-body text-center container" style="max-width:570px"> <ul class = "list-group" > <li class = "list-group-item text-left"> <div class = "author"> <p> Author </p> </div> <div class = "comment"> <p> Comment comment comment comment comment comment comment comment comment comment comment comment comment comment comment comment </p> </div> </li> <li class = "list-group-item text-left"> <div class = "author"> <p> Author </p> </div> <div class = "comment"> <p> Comment comment comment comment comment comment comment comment comment comment comment comment comment comment comment comment </p> </div> </li> <li class = "list-group-item text-left"> <div class = "author"> <p> Author </p> </div> <div class = "comment"> <p> Comment comment comment comment comment comment comment comment comment comment comment comment comment comment comment comment </p> </div> </li> </ul> <textarea name="comment" cols="74" rows="3"></textarea> <div class = "text-right"> <button type="button" class="btn btn-default" >Submit</button> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close </button> </div> </div> </div> </div> </li> <% end %> </ul> </div> </div> <% end %> As you can see each friend has some songs and for each song there can be comments. I'm trying to call the popups by dynamically generated id, but - funny thing - only the first one works... When I click comments button on the firs song (or it's later appearances) it works, but the rest of them doesn't. In the inspector I can see that all the modals' ids are generated correctly. I'm running out of ideas what to do about this. |
Rails - Add multiple records in one form Posted: 04 Sep 2016 07:20 AM PDT I have a User model and Todo model. I want to be able to add multiple todos using a single form. Routes: # Users resources(:users) do resources(:todos) end User model: class User < ApplicationRecord has_many :todos .... Todos controller: class TodosController < ApplicationController def new @user = User.find(params[:id]) @todos = Array.new(10) {@user.todos.build} end .... View for todos/new: <%= form_for([@user, :todos]) do |f| %> <% @todos.each do |todo| %> <%= f.text_field(:name, class: "form-control") %> <% end %> <%= f.submit "Save", class: "btn btn-primary" %> <% end %> What I get is: undefined method `model_name' for :todos:Symbol What am I doing wrong? I searched SO for doing multiple saves using one form, and I found this. |
Rails 4 Error: ActiveRecord::AssociationTypeMismatch Posted: 04 Sep 2016 07:34 AM PDT
Hey there, I am fairly new to Rails and I've managed to create a Favorite controller for my Items(Tools) and Users. I am displaying all Favorited Items(Tools) by a user correctly on his index. On the search view I provide links to favorite and unfavorite, but I am getting an error when I click on this link of a certain Item(Tool) I am getting this error in the browser when favoriting an item: ActiveRecord::AssociationTypeMismatch in ToolsController#favorite Tool(#46153692) expected, got NilClass(#20297664) The Request Parameters {"_method"=>"put", "authenticity_token"=>"vlWYHcp1K4Eu8WzjyEM8f6Eta9MNjgojtkr6RlG6n7121PGiWtXU8kDq9yXOfzGzw5grSc4GCqlcoK1UiLEsng==", "type"=>"favorite", #WhatMyUserDid "id"=>"1"} #MyUserId My goal is to add a favorited Item(Tool) for a User (=> Error), show favorited Items(Tools) on Users index view (works fine), and show the link to Favorite or Unfavorite depending on the Favorites of the current_user (not implemented yet) Here is my code: app/models/favorite_tool.rb class FavoriteTool < ActiveRecord::Base belongs_to :tool belongs_to :user end app/models/tool.rb class Tool < ActiveRecord::Base belongs_to :user # Favorited by users has_many :favorite_tools # just the 'relationships' has_many :favorited_by, through: :favorite_tools, source: :user # the actual users favoriting a tool mount_uploader :cover_filename, CoverUploader end app/models/user.rb class User < ActiveRecord::Base # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable has_many :tools # Favorite tools of user has_many :favorite_tools # just the 'relationships' has_many :favorites, through: :favorite_tools, source: :tool # the actual tools the user favorites mount_uploader :avatar_filename, AvatarUploader end app/controllers/tools_controller.rb class ToolsController < ApplicationController before_action :find_tool, only: [:show, :edit, :update, :destroy] # Add and remove favorite recipes # for current_user def favorite type = params[:type] if type == "favorite" current_user.favorites << @tool redirect_to :back, notice: 'You favorited #{@tool.title}' elsif type == "unfavorite" current_user.favorites.delete(@tool) redirect_to :back, notice: 'Unfavorited #{@tool.title}' else # Type missing, nothing happens redirect_to :back, notice: 'Nothing happened.' end end def index @favorites = current_user.favorites @tools = Tool.where(user_id: current_user).order("created_at DESC") @user = current_user end def search @tool = Tool.find(1) @tools = Tool.all.order("created_at DESC") end def show end def new @tool = current_user.tools.build end def create @tool = current_user.tools.build(tool_params) if @tool.save redirect_to tools_path else render 'new' end end def edit end def update if @tool.update(tool_params) redirect_to tools_path else render 'edit' end end def destroy @tool.destroy redirect_to tools_path end private def find_tool @tool = Tool.find(params[:id]) end def tool_params params.require(:tool).permit(:title, :subtitle, :url, :cover_filename) end end app/views/tools/index.html.haml %h2 My Favorite Tools - @favorites.each do |tool| = image_tag tool.cover_filename.url %h2= link_to tool.title, tool %p= tool.subtitle %p= link_to "Edit", edit_tool_path(tool) %p= time_ago_in_words(tool.created_at) app/views/tools/search.html.haml - @tools.each do |tool| = image_tag tool.cover_filename.url %h2= link_to tool.title, tool %p= tool.subtitle %p= link_to tool.user.try(:username), '/users/'+tool.user_id.to_s %p= link_to "Favorite", favorite_tool_path(@tool, type: "favorite"), method: :put %p= link_to "Unfavorite", favorite_tool_path(@tool, type: "unfavorite"), method: :put %p= link_to "Edit", edit_tool_path(tool) %p= time_ago_in_words(tool.created_at) app/config/routes.rb resources :tools do put :favorite, on: :member end I hope the provided data is enough, if not please tell me. I'm grateful for all Your replies. |
configuring VPS for Ruby on rails app...which version of Ruby to use? Posted: 04 Sep 2016 08:01 AM PDT I'm configuring my first VPS for my first ruby on rails app that I´m soon deploying to the web. I'm following this documentation https://gorails.com/deploy/ubuntu/16.04 it is going greate, but I just realised that my version of Ruby is ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-darwin15] and the recommended for the setup is ruby version 2.3.1. So do I have to update the ruby version on my computer to 2.3.1 or is it ok to deploy an app build on ruby 2.2.3 to an server running version 2.3.1. This might be a stupid question, but I just want to be sure because I lack experience and I´m setting up VPS for the first time. p.s The App soon to deployed is built in rails 4.2.5 |
My has_many - belongs_to tables in ruby on rails don't seem to be related. Posted: 04 Sep 2016 07:02 AM PDT I made 'hospital_review' table and 'hospital_review_comments' table with 1:N relationship on ruby on rails. 'hospital_review' table's migration file is like this. class CreateHospitalReviews < ActiveRecord::Migration def change create_table :hospital_reviews do |t| t.string :written_time t.string :writter t.integer :user_id t.string :category t.string :hospital_name t.text :content end end and 'hospital_review_comments's one is like this. def change create_table :hospital_review_comments do |t| t.integer :user_id t.integer :post_id t.string :writter t.string :written_time t.text :content t.timestamps null: false end end 'hospital_review' table's model file is like this. belongs_to :user has_many :hospital_review_comments 'hospital_review_comments' table's one is like this. belongs_to :user belongs_to :hospital_review I wanted to show each hospital review and the comments that are written on it, so I programmed the codes below in 'show.html.erb'. <% @post.hospital_review_comments.each do |comment| %> <p><strong><%=comment.user.username%></strong> <%=comment.content%></p> and this is show action in controller file. def show @post = HospitalReview.find(params[:id]) @hospital_comment_writer = User.where(id: session[:user_id])[0] end but the error occcured with message 'SQLite3::SQLException: no such column:'. I tried 'foregin_key' in hospital_review_comments table's model file, but it didn't work. I can't get the reason the error occurred. Plz help! |
Update attributes rails - No route matches [POST] Posted: 04 Sep 2016 06:49 AM PDT I'm trying to basically update my integration object attribute "filters". I have a integrations controller and what seems the proper actions to do so. But when I try to save after filling out the text-field I get this error No route matches [POST] , I understand what it's saying but isn't update a post? Here is my code for clarity. Controller def update @integrations = current_account.integrations.find(params[:id]) attrs = params.require(:integration).permit(:filters) if @integrations.update_attributes(attrs) redirect_to account_integration_path else render :filters end end def filters @integrations = current_account.integrations.find(params[:id]) end View <%= form_for @integrations, url: filters_account_integration_path do |f| %> <%= f.text_field :filters, class: "tag-autocomplete" %> <%= link_to "Save", account_integration_path, method: :post, class: [ "button", "button--modal" ] %> <% end %> Routes resources :integrations, only: [ :index, :destroy, :update ] do get "filters", on: :member end Hopefully that is enough info let me know if you need more? My basic question is why is this not updating the integration object? Isn't update a post? |
Ruby on Rails Tutorial (Michael Hartl) Chapter 2 Exercise 2.3.3.1 "Edit the user show page to display the content of the user’s first micropost." Posted: 04 Sep 2016 06:46 AM PDT Full descriptions of task sounds: Edit the user show page to display the content of the user's first micropost. (Use your technical sophistication (Box 1.1) to guess the syntax based on the other content in the file.) Confirm by visiting /users/1 that it worked. My first idea was to update app/views/users/show.html.erb into <p id="notice"><%= notice %></p> <p> <strong>Name:</strong> <%= @user.name %> </p> <p> <strong>Email:</strong> <%= @user.email %> </p> <p> <strong>Content:</strong> <%= @micropost.content %> </p> <%= link_to 'Edit', edit_user_path(@user) %> | <%= link_to 'Back', users_path %> But seems I haven't got idea behind task? Any suggestions from what I should start from? Biggest thanks for your responses) |
Update a table in bulk in activerecord Posted: 04 Sep 2016 06:26 AM PDT I want to update a table in bulk passed as an array from ajax params[:column1]= [1,2,3] params[:column2]= ['a','b'] I have a table column1 | column2 |column3 1 | a | true 2 | b | true I want to first find if not available then i want to insert a record. I tried the following model.where(:params[:column1] => params[:column1], :column2 => params[:column2]).first_or_create!(:column3 => true) The expected output is column1 | column2 |column3 1 | a | true 2 | b | true 1 | b | true 2 | a | true 3 | a | true 3 | b | true |
Rails Drop Down List Sort Values Posted: 04 Sep 2016 06:29 AM PDT I have an array that is populating a dropdown list in a view (erb) file. I want to have the values in the dropdown list sorted by values (it's a list of names Last, First... just want them sorted by last). This is what I have: <% if @users users_arr = [] @users.each do |u| users_arr << ["#{u.name}", u.id] end end first_selected_parent = @kid.users && @kid.users.first ? @kid.users.first.id : "" second_selected_parent = @kid.users && @kid.users.count > 1 ? @kid.users.last.id : "" %> I've googled and tried a number of things but haven't been able to figure it out yet. Thanks! |
default blank for boolean dropdown menu Posted: 04 Sep 2016 06:24 AM PDT I am creating an application where users can create apartment listings. The form asks users to specify whether there is an agent fee and if the apartment is furnished. In the apartment form partial (which is rendered in the create and edit apartment views), I have two dropdown menus for these boolean variables (furnished and agent_fee). I validate that these variables are present in the model validation: class Apartment < ActiveRecord::Base belongs_to :user validate :agent_fee_and_furnished_are_present def agent_fee_and_furnished_are_present if agent_fee.nil? errors.add(:agent_fee, "You must specify if there is an agent fee") end if furnished.nil? errors.add(:furnished, "You must specify if the apartment is furnished") end end end (I created a custom validation so FALSE would be allowed. If I validated the presence of the variables, FALSE would fail the .blank test that ruby runs.) My question is, how can I include a blank option as the first option in the dropdowns that will work in the create AND edit views? (I want to do this so the user is forced to select one of the options, and doesn't end up with a default because that's what was the first in the dropdown) I tried: <div class="field"> <%= f.label :agent_fee, "Is there an agent fee?" %><br> <%= f.select :agent_fee, options_for_select([['Yes', true], ['No', false]]), {:prompt => ""} %> </div> However, when this field is rendered in the edit apartment view, there is a blank prompt present, even if the agent_fee for an apartment the apartment was FALSE. (It seems that rails does a similar .blank? test which only overrides the prompt if the value is TRUE) So again, my question is, how can I include a blank option as the first option in the dropdowns that will work in the edit view (and only be displayed if the agent_fee variable is NIL and not FALSE) |
devise "user_signed_in?" method in rspec Posted: 04 Sep 2016 06:49 AM PDT I have a controller action which uses devise's "user_signed_in?" as a condition. The action looks like this: def show if user_signed_in? #do stuff end end But when I am testing this action in RSpec, the tests are failing because the code inside the if block never gets executed. Is there any way to stub the "user_signed_in?" method? |
Rails - Form_for error for undefined local variable? Posted: 04 Sep 2016 06:14 AM PDT I've been trying to setup a contact form but I keep getting errors and I just can't figure out what I'm doing wrong. The latest error I'm getting is: NameError in Contacts#new Showing .../app/views/contacts/new.html.erb where line #2 raised: undefined local variable or method `contact' for #<#<Class:0x007fa2933ca1f8>:0x007fa29a4df460> Did you mean? @contact concat Extracted source (around line #2): 1 2 3 4 5 6 <h1>Contact us</h1> <%= form_for(contact) do |f| %> <div class="field entry_box"> <%= f.label :name %> <%= f.text_field :name, class: "form-control entry_field" %> </div> My ContactsController class ContactsController < ApplicationController def new @contact = Contact.new end def create @contact = Contact.new(contact_params) if @contact.save redirect_to contacts_path, notice: "Thanks for contacting us!" else render :new end end private def contact_params params.require(:contact).permit(:name, :email, :message) end end Model class Contact < ApplicationRecord end Routes (relevant parts) resources :contacts, only: [:new, :create] get "contact" =>'contacts#new' post "contact" =>'contacts#create' View (new.html.erb) <h1>Contact us</h1> <%= form_for(contact) do |f| %> <div class="field entry_box"> <%= f.label :name %> <%= f.text_field :name, class: "form-control entry_field" %> </div> <div class="field entry_box"> <%= f.label :email %> <%= f.number_field :email, class: "form-control entry_field" %> </div> <div class="field entry_box"> <%= f.label :message %> <%= f.text_field :message, class: "form-control entry_field" %> </div> <div class="actions center space_big"> <%= f.submit "Submit", class: "btn btn-lg btn-success" %> </div> <% end %> Thanks for any assistance! |
ouath with facebook working only with developer account Posted: 04 Sep 2016 05:38 AM PDT I've set a oauth2.0 with devise registration through facebook to my app. The thing is that I am working in dev mode in localhost( sorry for my english). Now I can registrate through fb, and get user_name and email and save them to db. Everything works fine with registration, when I am using account to registrate that equals developers account. Example( in case my explanations are not straight forward). My developer account is anton@gmail.com. When I use it to registrate in my app - everything seems to go fine. I gain access to my app and my email and first_name are saved to db. But when I try to use some different fb account( like anton1@gmail.com ) I recieve, I recieve an error that my app is not configured properly and I have to contact admin tom gain permission. I s this OK for dev_mode or I configured something wrong? |
Rails - Best Gem(s) for (job) application form? Posted: 04 Sep 2016 06:26 AM PDT Hello and a wonderful sunday everyone! I'm starting out with Rails and just thought it would be a really good idea to develop a application form for potential employees. Now I'm looking for good solutions (Gems?) to fullfill my requirements to do so. The application contains: - Text field suchs as for name, adresses, ...
- Select fields
- Data fields for uploading your CV, ...
I already made it with Bootstrap and applied my own theme to it. I've designed the database concept as well. It's looking great and now I'm ready for the next step. What I would love to do next is that the applicant can upload the required files and they are saved in the database. I thought about using Papierclip for that. But the most important step would be that I'd like to save all the input in the database AND that I get each time a email with all the attachment and input as well. How can I achieve that relative uncomplicated? In short: - What Gem is recommended for uploading necessary documents and save it in the database?
- How can I achieve the notifation functionality such as after 'submit' all the input is stored in the database plus you get an email with all the input as well. Is there a recommended Gem available as well? Possibly it would be nice that it's useable with Gems like Paperclip.
- I thought about using Captchas as well. What do you think of it? I think you use Gems for Captchas in Rails as well...?
I'd love to hear your recommendations and solutions. I know that's no excuse but because I'm just starting out I would be happy to get to know best practise in this matter asap. If you have any additional tips it'd be awesome. |
Why aren't my comments in my forum saving to the database? Posted: 04 Sep 2016 06:41 AM PDT I'm using ruby on rails to create a forum website using a tutorial I found on youtube. I've gotten through 80% of it with no problem till now. I've rewatched the video 10 plus times to ensure no syntax errors or any other mishaps. Basically, comments people make on posts are not saving to the database, and hence they are not showing on the html views where I present them. I know they are not saving because I checked in the terminal the database of comments and it came back as 0 count. Here's my code in the different files... ROUTES.RB Rails.application.routes.draw do devise_for :users resources :posts do resources :comments end root 'posts#index' end MIGRATION FILE for create_comments class CreateComments < ActiveRecord::Migration[5.0] def change create_table :comments do |t| t.text :comment t.references :post, foreign_key: true t.references :user, foreign_key: true t.timestamps end end end comments_controller.rb class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) @comment = @post.comments.create(params[:comment].permit(:comment)) if @comment.save redirect_to post_path(@post) else render 'new' end end end _form.html.haml = simple_form_for([@post, @post.comments.build]) do |f| = f.input :comment = f.submit MODEL FILE comment.rb class Comment < ApplicationRecord belongs_to :post belongs_to :user end LOG WHEN FORM IS SUBMITTED Started POST "/posts/2/comments" for ::1 at 2016-09-04 23:00:46 +1000 Processing by CommentsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"/Un6QNWL4BIUbjH5VYMhLRatTq2hokcKnZ3Jb4WzTlvhuZ5AN3gFkA5VHN2E6zsm0iDIx/sKarEfID7Nx4WwwQ==", "comment"=>{"comment"=>"1"}, "commit"=>"Create Comment", "post_id"=>"2"} Post Load (0.3ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]] (0.1ms) begin transaction (0.1ms) rollback transaction Completed 500 Internal Server Error in 26ms (ActiveRecord: 0.5ms) ActionView::MissingTemplate (Missing template comments/new, application/new with {:locale=>[:en], :formats=>[:html], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :haml, :jbuilder]}. Searched in: * "/Users/koz/Desktop/forum/app/views" * "/Users/koz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/devise-4.2.0/app/views" ): app/controllers/comments_controller.rb:11:in `create' Rendering /Users/koz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb within rescues/layout Rendering /Users/koz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb Rendered /Users/koz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (14.6ms) Rendering /Users/koz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb Rendered /Users/koz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (5.4ms) Rendering /Users/koz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb Rendered /Users/koz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (2.9ms) Rendered /Users/koz/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb within rescues/layout (297.8ms) |
Ruby On Rail - website is too heavy Posted: 04 Sep 2016 05:29 AM PDT I am using ROR on CentOS 6 with 2 web server and 1 database server. Some times message is coming The website is under heavy load ... with using Passenger 4.0.21 with Ruby 1.8.7 and Apache 2.2.15. Server is working with the default settings. Below is the response for passenger-status: Version : 4.0.21 Date : Thu Dec 12 02:02:44 -0500 2013 Instance: 20126 ----------- General information ----------- Max pool size : 6 Processes : 6 Requests in top-level queue : 0 ----------- Application groups ----------- /home/web/html#default: App root: /home/web/html Requests in queue: 100 * PID: 20290 Sessions: 1 Processed: 53 Uptime: 24h 3m 5s CPU: 0% Memory : 634M Last used: 23h 16m 8 * PID: 22657 Sessions: 1 Processed: 37 Uptime: 23h 15m 55s CPU: 0% Memory : 609M Last used: 22h 44m * PID: 29147 Sessions: 1 Processed: 146 Uptime: 20h 47m 48s CPU: 0% Memory : 976M Last used: 18h 20m * PID: 22216 Sessions: 1 Processed: 26 Uptime: 10h 3m 19s CPU: 0% Memory : 538M Last used: 9h 44m 4 * PID: 23306 Sessions: 1 Processed: 75 Uptime: 9h 43m 22s CPU: 0% Memory : 483M Last used: 8h 44m 4 * PID: 25626 Sessions: 1 Processed: 115 Uptime: 8h 46m 42s CPU: 0% Memory : 540M Last used: 7h 59m 5 |
Rails Last_enable Devise check User Online Posted: 04 Sep 2016 07:45 AM PDT I am using a gem for devise called Last_enable https://github.com/ctide/devise_lastseenable and I would like to implement an if statement on my user view , to display a logo "Online" if this statement is true . My user controller : def online online = User.where('last_seen > ?', 5.minutes.ago) end the 'online' query works in console and return a user. I just dont really know how to implement that on my view, or do a check if this statement is valid : <% if #What should I write here to check if my user is online ? %> <%= image-tag('assets/true.png') %> <% else %> <%= image-tag('assets/point_red.png') %> <% end %> Thanks in advance for your help ! |
How to create a shopify product with many variants Posted: 04 Sep 2016 08:09 AM PDT Anyone knows how to create new products with variants? In the Ruby on Rails world, we have our :has_many , then do this: Product.create!(...).variants.build(...).save That would create a product and its association variant . For Shopify, I have no idea: user_products.map do | up | new_products = ShopifyAPI::Product.build(...) up.variants.each do |variant| new_products.variants.build(...) end new_products.save end Doing just that I got: ActiveResource::ServerError (Failed. Response code = 501. Response message = Not Implemented.) In my case, this is not ideal: ShopifyAPI::Product.new( { ..., variants: [ ... ] } ).save |
OneLogin SSO with multiply idPs Posted: 04 Sep 2016 05:17 AM PDT One of our clients has OneLogin as identity provider and we were asked to implement SSO. My question is, how could I implement multiple idPs(few clients) on OneLogin using same "sign in with OneLogin" option? Thanks. |
Wrong content type for paperclip uploads during RSpec tests Posted: 04 Sep 2016 04:10 AM PDT Using ActionDispatch#fixture_file_upload method for rspec tests, I'm having trouble setting the content type for a file. For example... 1) Create an "uploaded" file and set content type to text/xlsx . file = fixture_file_upload("spreadsheet.xlsx", "text/xlsx") } 2) The content_type here is the desired "text/xlsx". So far so good. [1] pry(#<CreateUpload>)> file => #<ActionDispatch::Http::UploadedFile:0x007fd786f0a518 @content_type="text/xlsx", @headers= "Content-Disposition: form-data; name=\"some_file_upload[upload_attributes][asset]\"; filename=\"spreadsheet.xlsx\"\r\nContent-Type: text/xlsx\r\nContent-Length: 346615\r\n", @original_filename="spreadsheet.xlsx", @tempfile= #<File:/var/folders/fj/c7n1899d0270qj43swmpxwy80000gn/T/RackMultipart20160904-78785-1abvz6q.xlsx>> 3) Double checking, it's still "text/xlsx" content_type... [2] pry(#<CreateUpload>)> file.content_type => "text/xlsx" 4) But when I save to Paperclip, content type changes to "application/zip" ?!? [3] pry(#<CreateUpload>)> upload = Upload.new(asset: file) => #<Upload:0x007fd77d5694b8 id: nil, uploadable_id: nil, uploadable_type: nil, created_at: nil, updated_at: nil, asset_file_name: "spreadsheet.xlsx", asset_content_type: "application/zip", asset_file_size: 346615, asset_updated_at: Sun, 04 Sep 2016 10:55:44 UTC +00:00> 5) Now my validation blows up because only "text/xlsx" is allowed: [5] pry(#<CreateUpload>)> upload.save! ActiveRecord::RecordInvalid: Validation failed: Asset content type is invalid, Asset is invalid from /Users/mace/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activerecord-4.2.6/lib/active_record/validations.rb:79:in `raise_record_invalid' |
Rails 4: How do I properly link_to edit_path on index? Posted: 04 Sep 2016 03:46 AM PDT I am new to rails and stuck with a probably easy to answer question. I have a controller and model (Tools / Tool) and I linked the edit_path from the show page of the Tool. But how can I also link it from my index and search page? Here is the relevant code: /app/controllers/tools_controller.rb class ToolsController < ApplicationController before_action :find_tool, only: [:show, :edit, :update, :destroy] def index @tools = Tool.where(user_id: current_user).order("created_at DESC") @user = current_user end def search @tools = Tool.all end def show end def new @tool = current_user.tools.build end def create @tool = current_user.tools.build(tool_params) if @tool.save redirect_to tools_path else render 'new' end end def edit end def update if @tool.update(tool_params) redirect_to tools_path else render 'edit' end end def destroy @tool.destroy redirect_to tools_path end private def find_tool @tool = Tool.find(params[:id]) end def tool_params params.require(:tool).permit(:title, :subtitle, :url) end end /app/views/tools/show.html.haml %h1= @tool.title = link_to "Back", :back = link_to @tool.user.try(:username), '/users/'+@tool.user_id.to_s = link_to "Edit", edit_tool_path(@tool) = link_to "Delete", tool_path(@tool), method: :delete, data: { confirm: "Are you sure?" } enter code here /app/views/tools/index.html.haml %h2 My Tools - @tools.each do |tool| %h2= link_to tool.title, tool %p= tool.subtitle %p= link_to "Edit", edit_path %p= time_ago_in_words(tool.created_at) -if @user.use_gravatar? = image_tag gravatar_for @user - else = image_tag @user.avatar_filename.url %h1= @user.username = link_to "Edit", edit_user_registration_path /app/views/tools/search.html.haml - @tools.each do |tool| %h2= link_to tool.title, tool %p= tool.subtitle %p= link_to tool.user.try(:username), '/users/'+tool.user_id.to_s %p= link_to "Edit", edit_path %p= time_ago_in_words(tool.created_at) I hope the provided data is enough, if not please tell me. I'm grateful for all Your replies. |
Syntax error on rake db:schema:dump Posted: 04 Sep 2016 04:44 AM PDT I try to connect mysql with ruby, I follow this video https://www.youtube.com/watch?v=GY7Ps8fqGdc but on 23:30 in video, I got error with rake db:schema:dump , I have no idea, this is my error: irb(main):016:0> rake db:schema:dump SyntaxError: (irb):16: syntax error, unexpected tLABEL rake db:schema:dump ^ from /usr/local/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/console.rb:65:in `start' from /usr/local/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/console_helper.rb:9:in `start' from /usr/local/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:78:in `console' from /usr/local/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands/commands_tasks.rb:49:in `run_command!' from /usr/local/lib/ruby/gems/2.3.0/gems/railties-5.0.0.1/lib/rails/commands.rb:18:in `<top (required)>' from bin/rails:4:in `require' from bin/rails:4:in `<main>' |
could not connect to server: No such file or directory (PG::ConnectionBad) Posted: 04 Sep 2016 04:43 AM PDT Yesterday wasn't this error. I didn't make any changes in my application. Just went to sleep and now I get this. Error: home/dartnyan/.rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/ active_record/connection_adapters/ postgresql_adapter.rb:651:in `initialize': could not connect to server: No such file or directory (PG::ConnectionBad) Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? database.yml default: &default adapter: postgresql pool: 5 imeout: 5000 development: adapter: postgresql database: shop_development pool: 5 username: dartnyan password: kurt1245 test: adapter: postgresql encoding: unicode database: shop_test pool: 5 username: dartnyan password: kurt1245 |
{:onChange => "#{remote_function(:url => {:action => "list_user"}, Posted: 04 Sep 2016 05:31 AM PDT I am migrating from rails 2.3.5 to rails 4 on ruby 2.3. I got this error NoMethodError in User#all Showing c:/site/simple_cms/app/views/user/all.erb where line #36 raised: undefined method `remote_function' for #<#<Class:0x0000000c5c6190>:0x0000000bff7408> Extracted source (around line #36): 34 35 36 37 38 39 <div class="text-input-bg"><%= select :user_type, :type, [["#{t('admin')}","Admin"], ["#{t('employee_text')}","Employee"],["#{t('student_text')}","Student"],["#{t('parent')}","Parent"]], {:prompt => "#{t('select_a_role')}"}, {:onChange => "#{remote_function(:url => {:action => "list_user"}, :with => "'user_type='+value", :before => "Element.show('loader')", :success => "Element.hide('loader')" |
allow_any_instance_of and allow using the instance_double is not working properly Posted: 04 Sep 2016 02:51 AM PDT Just want to ask if you encounter that when you refactor your spec that before you used the allow_any_instance_of then you change it to allow it didn't work as what you expect. As we all know in the documentation the allow_any_instance_of was already deprecated and they're encourage us to use the allow . I still don't know why it didn't work. Btw, I can't reproduce my code here as this is own by company but the structure is like this. Before feature `Something Page Spec here`, retry: 0, js: true do # some `let` here before do sign_in user setup_something_here end describe 'feature here' do let( :user ) { create( :user ) } before do allow_any_instance_of( ActionDispatch::Request ).to receive( :headers ) { { 'something' => 'here' } } end context 'something here' do # then some expectation here end end end After feature `Something Page Spec here`, retry: 0, js: true do # some `let` here before do sign_in user setup_something_here request = instance_double( ActionDispatch::Request ) allow( request ).to receive( :headers ) { { 'something' => 'here' } } end describe 'feature here' do let( :user ) { create( :user ) } context 'something here' do # then some expectation here end end end I did pry when I stubbed it in before I can get the correct value but then in the after it's already nil. I'm confused why it didn't work. Hope there some can help me with this confusion. Thanks! |
Rails 4 DB Migration Error: undefined method `to_sym' for nil:NilClass Posted: 04 Sep 2016 03:23 AM PDT I am relatively new to rails and in the process of coding an application. So far the app itself works great. Lately I wanted to migrate something like this: (Updated) class ChangeStuffFromTools < ActiveRecord::Migration def change change_column :tools, :shares, :integer, :default => 0 change_column :tools, :views, :integer, :default => 0 change_column :tools, :likes, :integer, :default => 0 change_column :tools, :favorites, :integer, :default => 0 change_column :tools, :featured, :boolean, :default => false end end I get this error: $ rails g migration remove_stuff_from_tools invoke active_record create db/migrate/20160904090608_remove_stuff_from_tools.rb Jonas@JONAS_PC ~/gitapps/ocubit (master) $ rake db:migrate == 20160904090608 RemoveStuffFromTools: migrating ============================= -- remove_column(:tools, :featured, :boolean) rake aborted! StandardError: An error has occurred, this and all later migrations canceled: undefined method `to_sym' for nil:NilClass c:/Users/Jonas/gitapps/ocubit/db/migrate/20160904090608_remove_stuff_from_tools.rb:3:in change' c:inmigrate' NoMethodError: undefined method to_sym' for nil:NilClass c:/Users/Jonas/gitapps/ocubit/db/migrate/20160904090608_remove_stuff_from_tools.rb:3:in change' c:in `migrate' Tasks: TOP => db:migrate (See full trace by running task with --trace) How can I possibly fix it, I mean I somehow need access to my database to edit it :) |
No comments:
Post a Comment