Extending Rails 4 engine models with concerns Posted: 06 Dec 2016 07:26 AM PST I am trying to extend a model from engine 1 with a concern from engine 2 through an app initializer, but I'm getting some weird behavior, here's what I've got: Concern module Engine2 module Concerns module MyConcern extend ActiveSupport::Concern included do puts "Concern included!" end def jump puts 'Jumping!!!!' end end end end Initializer require 'engine2/my_concern' module Engine1 class Member include Engine2::Concerns::MyConcern end end When I boot up the application, I see as expect the Concern included! message in the console, and the Member class can call the method jump , but as soon as I change any code in the host app I get the following error: NoMethodError (undefined method 'jump' for #<Engine1::Member:0x007fe7533b4f10>) and I have to reload the server, then it works fine again until I make another change in the host app, then it throws the error again, why is this happening and how can I avoid it? Is there a better place where I should perform the class opening to include the concern instead of the initializer? |
Puma Rails 5 binding.pry only available for 60 seconds before timeout Posted: 06 Dec 2016 07:25 AM PST Puma times out my request when I'm using binding.pry . In my controller def new require 'pry' binding.pry end I then make a request that hits the controller and enter the pry session. After 60 seconds Puma? times out my request, restarts a worker and subsequently blows up by debugging session. [1] pry(#<Agent::ClientsController>)> [3522] ! Terminating timed out worker: 3566 [3522] - Worker 0 (pid: 4171) booted, phase: 0 I generated this app with suspenders if that matters. How do I extend my debugging session in rails 5? |
Connect student_id to submission_id in Rails Posted: 06 Dec 2016 07:41 AM PST I was trying to connect my student_id to the submission_id, but it's not working. I have a join table which is called submissionstudent. Student Controller.rb: class StudentsController < ApplicationController before_action :set_student, only: [:show, :edit, :update, :destroy] # GET /students # GET /students.json def index @students = Student.all end # GET /students/1 # GET /students/1.json def show end # GET /students/new def new @student = Student.new end # GET /students/1/edit def edit end # POST /students # POST /students.json def create @student = Student.new(student_params) respond_to do |format| if @student.save format.html { redirect_to @student, notice: 'Student was successfully created.' } format.json { render :show, status: :created, location: @student } else format.html { render :new } format.json { render json: @student.errors, status: :unprocessable_entity } end end end # PATCH/PUT /students/1 # PATCH/PUT /students/1.json def update respond_to do |format| if @student.update(student_params) format.html { redirect_to @student, notice: 'Student was successfully updated.' } format.json { render :show, status: :ok, location: @student } else format.html { render :edit } format.json { render json: @student.errors, status: :unprocessable_entity } end end end # DELETE /students/1 # DELETE /students/1.json def destroy @student.destroy respond_to do |format| format.html { redirect_to students_url, notice: 'Student was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_student @student = Student.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def student_params params.require(:student).permit(:name) end end Submission Controller.rb: class SubmissionsController < ApplicationController before_action :set_submission, only: [:show, :edit, :update, :destroy] before_action :set_form # GET /submissions/new def new @submission = Submission.new @all_students = Student.all @submission_student = @submission.submissionstudent.build end # GET /submissions/1/edit def edit end # POST /submissions # POST /submissions.json def create @submission = Submission.new(submission_params) @submission.form_id = @form.id respond_to do |format| if @submission.save format.html { redirect_to @form, notice: 'Submission was successfully created.' } format.json { render :show, status: :created, location: @submission } else format.html { render :new } format.json { render json: @submission.errors, status: :unprocessable_entity } end end end # PATCH/PUT /submissions/1 # PATCH/PUT /submissions/1.json def update respond_to do |format| if @submission.update(submission_params) format.html { redirect_to @submission, notice: 'Submission was successfully updated.' } format.json { render :show, status: :ok, location: @submission } else format.html { render :edit } format.json { render json: @submission.errors, status: :unprocessable_entity } end end end # DELETE /submissions/1 # DELETE /submissions/1.json def destroy @submission.destroy respond_to do |format| format.html { redirect_to submissions_url, notice: 'Submission was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_submission @submission = Submission.find(params[:id]) end def set_form @form = Form.find(params[:form_id]) end # Never trust parameters from the scary internet, only allow the white list through. def submission_params params.require(:submission).permit(:conflict, :computer, :extra_time, :am_pm) end end Model Student.rb: class Student < ActiveRecord::Base has_many :submissionstudent has_many :submissions, :through => :submissionstudent end Model Submission.rb: class Submission < ActiveRecord::Base belongs_to :form has_many :submissionstudent has_many :students, :through => :submissionstudent end Join table model Studentsubmission.rb: class Submissionstudent < ActiveRecord::Base belongs_to :submission belongs_to :student end Tell me if you need any more code, Thanks for your help |
show already selected items in rails select drop down Posted: 06 Dec 2016 07:23 AM PST I have a select box in rails. When editing the records, I want the previously selcted items to be highlighted. I have <div class="field"> <td><%= f.label :keywords %>(Use Control-Click to select multiple keywords)</td> <td> <%= f.select :keywords, options_for_select(@keywords, :selected => @keywords), {:include_blank => false}, {:multiple => true, :size =>10} %> </div> I tried a couple of variations on the :selected => statement above but can't get what I want. What I'm looking for is When a user edits a record, the f.select will have the selections that are in the database pre selected. I do see a "Gotcha" here in that even if the items are pre selected, if the user clicks on any item without a Control-click, then the pre selected items are lost. -------- update----------- form for <%= form_for @bedsheet_line, :html => { :class => 'form-horizontal', multipart: true} do |f| %> |
Rails app + separate admin panel Posted: 06 Dec 2016 07:06 AM PST I want to make an app which allows people to register for certain type of event. It wouldn't require signing up - you just choose a city, hour, and fill in the form with your data, click on "Register" or "Book" and that's all. List of cities will change from time to time, and I obviously need to create new events - in different cities, with different addresses etc. So for a regular user,it's just a simple page, but for admin there should be options for creating new events, showing all people registered for an event etc. I'm aware of Devise, AdminRails, CanCanCan, but ad a beginner I'm not sure how to hide signing up/logging possibility from a regular user. Devise will make my app accessible after signing in and it's not my intention. I want regular app with a few views and form, and in some sense seperate admin panel with regular CRUD - create an event, list events, list users, delete events, delete users. I'll be greateful for any hints. |
CoffeeScript not working when appending content through ajax Posted: 06 Dec 2016 07:58 AM PST Hello I'm working with rails and have been trying to make ajax requests when submiting forms for comments so the result is appended to the list of comments. I've got it to work thanks to this video: https://www.youtube.com/watch?v=K-sns5tNdTY . Later I decided to add answers to my comments, which I implemented with a new model and made a button with coffeescript on each comment to show the answers and a form for a new answer to that specific comment (the default css state is hidden). And then append the answers the same way I've done with the comments. It was kind of a pain in the ass but got it to work. Now the problem I have is that when adding a comment, the "Responder" button on the appended comment refreshes the page instead of working like it does for the other comments (showing the section that is hidden). This is how I render the comments and the form (sorry for it being in spanish): <div id="seccion-comentarios" class="border-element-sm-div" style="overflow: hidden"> <h3 style="width: 500px">Comentarios</h3> <div id="comentarios"> <%= render @comentarios %> </div> <% if @comentarios.count <= 0 %> <p style="font-style: italic; color: grey; margin-left: 10px"> Aún no hay comentarios. Haz uno!</p> <% end %> <% if usuario_signed_in? %> <div style="overflow: auto"> <%= render :partial => 'comentarios/form' %> </div> <% end %> </div> This is the form for my comments (views/comentarios/form): <%= form_for @comentario , remote: true do |f| %> <%= f.hidden_field :favor_id, value: @favor.id%> <%= f.label :texto, "Escribe un comentario:" %> <br/> <%= f.text_area :texto, required: true,class: "form-control", style: "width: 99%; max-width: 99%"%> <div style="float: right; padding-top: 10px; margin-right: 1%"> <%= f.submit "Comentar", :class=>'btn btn-primary'%> </div> <% end %> And this is the create.js.erb for that inside views/comentarios $('#comentarios').append($("<%= j render @comentario %>").hide().fadeIn(500)); $('#comentario_texto').val(""); Then for each comment I render this (views/comentarios/_comentario.html.erb) : <div class="border-gau-sm" style="overflow: auto"> <div> Here comes the info of my comment </div> <div style="float: right; margin-top: -10px; margin-bottom: -2px;"> <a class= "respuestas-link btn btn-primary btn-xs" data-section-id="respuestas-seccion-<%=comentario.id%>" href="#"> Respuestas <span class="caret" style=""></span> </a> </div> <section id="respuestas-seccion-<%=comentario.id%>" style="display: none"> <br/> <div> Here's what I want to show </div> </section> </div> Finally the coffeescript that get the answers (#respuestas-seccion) to show is this: $(document).on 'turbolinks:load', -> $('.respuestas-link').click (event) -> event.preventDefault() commentSectionId = $(this).data('sectionId') $('#' + commentSectionId).fadeToggle() I've tried setting the default state of the answer section to be visible as to see if it was rendered correctly (removing the display:none in this line: <section id="respuestas-seccion-<%=comentario.id%>" style="display: none"> in _comentarios.html.erb ). It turned out it was, and I am able to post an answer. But the button that toggles that section, is still reloading the page. Maybe it has something to do with the $(document).on 'turbolinks:load', -> in the coffeescript? Any ideas? Thanks for your time and hope I could explain myself so you can help! |
Sending mail with embedded image in Ruby Posted: 06 Dec 2016 06:46 AM PST I want to send a mail with an attached image and embed this image in html. As a source for tag , What should I write and is there any missing header parts such a content_type ? When I am doing real test, I send to a mail to my gmail account. I can see there is an attachment with name "unnamed" and I could not display image even when I download. Gem: Pony require 'pony' Pony.override_options = { :via => :test } Pony.mail( :to => 'foo@bar', :from => 'abc@abc.com', :subject => 'test123', :body => "<h1><strong>Dear X, check the newsletter ,<br></strong></h1> <img src='attached image' />", :attachments => {"happy_image.jpg" => File.read("happy_image.jpg")} ) puts Mail::TestMailer.deliveries output: Date: Tue, 06 Dec 2016 17:23:05 +0300 From: abc@abc.com To: foo@bar Message-ID: <5846c9ca183d6_5983c9fd899060@MW7BIQ12TKYHQC.mail> Subject: test123 Mime-Version: 1.0 Content-Type: multipart/mixed; boundary="--==_mimepart_5846c9caf15a_5983c9fd8989e5"; charset=UTF-8 Content-Transfer-Encoding: 7bit ----==_mimepart_5846c9caf15a_5983c9fd8989e5 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit <h1><strong>Dear X, check the newsletter ,<br></strong></h1> <img src='' /> ----==_mimepart_5846c9caf15a_5983c9fd8989e5 Content-Type: image/jpeg; filename=happy_image.jpg Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename=happy_image.jpg Content-ID: <happy_image.jpg@MW7BIQ12TKYHQC> /9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQE BQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/ 2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAHiAuMDASIAAhEBAxEB/8QA HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK FhcYGQ== ----==_mimepart_5846c9caf15a_5983c9fd8989e5-- |
angular2 formBuilder group causes nesting of params Posted: 06 Dec 2016 07:45 AM PST I have the following formBuilder in angular2: constructor( private formBuilder: FormBuilder) { this.form = formBuilder.group({ id: [], title: ['', Validators.required], dates: formBuilder.group({ start_date: ['', Validators.required], end_date: ['', Validators.required] }, {validator: this.checkDates}) }); } dates is in a separate group, this is for validation purposes. onSubmit calls this service method: update(academicTerm: AcademicTerm): Observable<AcademicTerm> { let headers = new Headers(); headers.append('Content-Type', 'application/json'); return this.http .patch(this.endpointUrl + academicTerm.id, JSON.stringify(academicTerm), {headers}) .map(this.extractData) .catch(this.handleError); } When I check the backend (Rails5 API server) I can see this param set: Parameters: {"id"=>"3", "title"=>"Term Title", "dates"=>{"start_date"=>"2016-11-27", "end_date"=>"2016-12-01"}, "academic_term"=>{"id"=>"3", "title"=>"Term CL"}} Note in the academic_term hash that start_date and end_date are not present. On the Rails side of things I have strong params set up like this: def academic_term_params params.require(:academic_term).permit(:id, :title, :start_date, :end_date) end I have tried setting the nested dates object in strong params: def academic_term_params params.require(:academic_term).permit(:id, :title, :dates => [:start_date, :end_date]) end Which has no affect (dates is not an associated attribute?). So while I can update title I cannot update the dates. Is there a way to flatten the params sent from angular to be something like this: Parameters: {"id"=>"3", "title"=>"Term Title", "start_date"=>"2016-11-27", "end_date"=>"2016-12-01"} Or is there a way to fix it on the Rails side? |
The standard way to update extra attribute of join model - Rails Posted: 06 Dec 2016 06:48 AM PST here comes to the newbie of rails again. Actually I have asked a similar question in this:Having trouble in updating join model extra attributes in has_many through association - Rails, but thought that I have asked in a wrong direction and a complicated way, so would like to open a new question that ask in a simpler and more precise way. Would like to know when I have an extra attribute in the join model of has_many through: , what is the standard way to save and update the extra attribute of the join model. Below is just an example and what I have tried: In a Forum , A User has many Group ; A Group has many User , through GroupUser . class User < ApplicationRecord has_many :group_users has_many :groups, through: :group_users end class Group < ApplicationRecord belongs_to :forum has_many :group_users has_many :users, through: :group_users end class GroupUser < ApplicationRecord belongs_to :group belongs_to :user end class Forum < ApplicationRecord has_many :groups end Due to some reason, I may want to add an extra attribute forum_id to the join modelGroupUser so it becomes like: UML diagram What would be the correct way to do the create and update in the controller? I have tried something like: def create @forum = Forum.find(params[:forum_id]) @group = @forum.groups.build(group_params) @group.group_users.each do |join| join.forum_id = @group.forum_id end @group.save end def update @group = Group.find(params[:id]) @group.group_users.each do |join| join.forum_id = @group.forum_id end @group.update(group_params) end private def group_params params.require(:group).permit(:name, user_ids: []) end I can save the forum_id in the create ; however, the forum_id will be nil when doing an update in the association. It has bordered me for more than twenty hours already, I really want to know the standard way to save and update the extra attribute of the join model. Thanks for reading my words. Appreciate any comments. Every suggestion will alleviate my headache right now. Thanks. |
Saving (multiple) nested images via Paperclip doesn't work Posted: 06 Dec 2016 06:16 AM PST I get an error when trying to save / view a picture into / from a nested table. I want to store multiple photos that belong to one blog, hence the nested set-up. Several answers to similar questions on SO didn't lead me to the solutions. The error: NoMethodError in Blogs#show Showing /home/ubuntu/workspace/MyDashboard/app/views/blogs/show.html.erb where line #11 raised: undefined method `photo' for # I don't think the picture is saved at all, and/or the "photo" attribute it not known. Blog.rb: class Blog < ApplicationRecord validates_presence_of :date, :story has_many :blog_images, :dependent => :destroy accepts_nested_attributes_for :blog_images, reject_if: :all_blank, allow_destroy: true end Blog_Image.rb class BlogImage < ApplicationRecord belongs_to :blog has_attached_file :photo, :styles => { :small => "150x150>", :large => "320x240>" } validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\z/ end Routes.db: resources :blogs do resources :blog_images end Controller: def new @blog = Blog.new @blog.blog_images.build end def create @blog = Blog.new(blog_params) if @blog.save redirect_to blogs_path else render 'new' end end (...) private def blog_params params.require(:blog).permit(:story, :date, blog_images_attributes: [:id, :blog_id, :photo]) end Input form: <%= form_for(@blog, :html => {:multipart => true}) do |f| %> <div class="field"> <%= f.label :date %> <%= f.date_field :date %> </div> <div class="field"> <%= f.label :story %> <%= f.text_area :story %> </div> <%=f.fields_for :blog_images do |i| %> <%= i.file_field :photo %> <% end %> <div class="actions"> <%= f.submit %> </div> <% end %> View: <p> <%= image_tag @blog.blog_images.photo.url(:small) %> </p> The form is saving but when I want to view it, I get the above error. I'd appreciate your help! |
creating geoJson with Polygons & Multipolygons in Rails Posted: 06 Dec 2016 06:12 AM PST I'm currently working on a small Rails Application which displays data on a map. It's done with Ruby on Rails (3.2) and the Javascript Leaflet library (1.0). The data is sitting in a SAP Hana database and is queried over the standard activerecord/odbc adapter. The setup might be unconventional, but it's not possible to switch anymore. The GeoJson file (which is actually a hash) is generated in the controller, similar to blogposts like: http://vladigleba.com/blog/2013/11/14/using-mapbox-with-ruby-on-rails/ http://www.bryceholcomb.com/2015/02/10/mapbox-and-rails/ In the view, I simply load the created json with $.getJSON and placing the data with Leaflet's LgeoJSON Method on the map. The controller looks like this: class Namespace::Controllername < ApplicationController def getjson @sql = 'select * from table' @results = ActiveRecord::Base.connection.exec_query(@sql) @results = @results.to_hash @geojson = Hash.new @features = [] @geojson[:type] = "FeatureCollection" @geojson[:features] = @features @results.each do |result_hash| @features << { type: 'Feature', geometry: { type: 'Point', coordinates: [result_hash["long"], result_hash["lat"]] }, properties: { id: result_hash["ID"], name: result_hash["NAME"] } } end @geojson end end It works very well, but now I want to replace the point coordinates with polygons and multipolygons to show shapes on the map instead of just points. And there's my problem. I' looking desperately for some solution. Target is to save the coordinates in the database. But I' not sure which filetype to choose. I tried to save them as string, but cannot get rid of the quotation marks. Please, can anyone help? |
SSL certificate error when i try to launch ruby soft Posted: 06 Dec 2016 06:06 AM PST Here is my prob, i'm trying to use this : https://github.com/yatish27/linkedin-scraper So i took it from the beginning and made the first step, installing the gem and then make require 'linkedin-scraper' the irb returns true ! And then i try the second command : profile = Linkedin::Profile.new("http://www.linkedin.com/in/jeffweiner08") then i got an ssl error, and i can't find how to fix it on google. Could someone help me ? Here is the message : irb(main):002:0> profile = Linkedin::Profile.new("http://www.linkedin.com/in/jeffweiner08") OpenSSL::SSL::SSLError: SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:933:in `connect_nonblock' from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:933:in `connect' from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:863:in `do_start' from C:/Ruby23-x64/lib/ruby/2.3.0/net/http.rb:858:in `start' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/net-http-persistent-2.9.4/lib/net/http/persistent.rb:700:in `start' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/net-http-persistent-2.9.4/lib/net/http/persistent.rb:631:in `connection_for' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/net-http-persistent-2.9.4/lib/net/http/persistent.rb:994:in `request' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/mechanize-2.7.5/lib/mechanize/http/agent.rb:274:in `fetch' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/mechanize-2.7.5/lib/mechanize/http/agent.rb:993:in `response_redirect' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/mechanize-2.7.5/lib/mechanize/http/agent.rb:315:in `fetch' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/mechanize-2.7.5/lib/mechanize.rb:464:in `get' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/linkedin-scraper-2.1.1/lib/linkedin-scraper/profile.rb:33:in `initialize' from (irb):2:in `new' from (irb):2 from C:/Ruby23-x64/bin/irb.cmd:19:in `<main>' |
Ruby hash access value from string array Posted: 06 Dec 2016 06:46 AM PST I have an hash like below: hash = {"a": [{"c": "d", "e": "f"}] } Normally we can access it like hash["a"][0]["c"] . But, I have a string like: string = "a[0]['c']" (This can change depending upon user input) Is there any easy way to access hash using above string values? |
Emberjs PATCH and POST to Rails unpermitted parameters Posted: 06 Dec 2016 05:50 AM PST So I've got an EmberJS and Rails API going. I am using Active Model Serializer. I have the following Active Model Serializer intializer config: active_model_serializer.rb ActiveModelSerializers.config.adapter = :json_api api_mime_types = %W( application/vnd.api+json text/x-json application/json ) Mime::Type.register 'application/vnd.api+json', :json, api_mime_types At the moment, my Ember app is able to fetch data from my Rails API fine. It is having problem sending updated user info to my Rails server however. I am getting an error on my Rails server log: Unpermitted parameters: data, id, user My ember appears to be sending the paramters: { "data"=>{ "id"=>"2", "attributes"=>{ "first-name"=>"James", "last-name"=>"Raynor", "username"=>"Jimobo", "email"=>"jim@gmail.com", "photo"=>{ "photo"=>{ "url"=>nil } } }, "type"=>"users" }, "id"=>"2", "user"=>{ } } Note: I only changed the username from Jimo to Jimobo . When I was building my Rails API, I was using Active Model Serializer and the strong parameters looks something like: Strong Parameters def user_params params.permit(:first_name, :last_name, :username, :email, :password, :password_confirmation, :photo, friend_ids: []) end Do I really have to go through every one of my strong parameter declarations and modify them to be like this: params.require(:data).require(:attributes).permit(...); Or is there some magical solution I am not doing correctly? In this Github discussion https://github.com/rails-api/active_model_serializers/issues/1027#issuecomment-126543577, a user named rmcsharry mentioned he didn't really need to modify anything and it worked out of the box......although he didn't show what his strong parameters looked like. |
Ruby - substituting characters in a string with sequential elements of an array Posted: 06 Dec 2016 06:49 AM PST I have a string: a = 'bla \n bla \n bla \n' And an array: b = ['1', '2', '3'] I want to search through the string, and replace every nth instance of \n with the (n-1)th element from the array, resulting in: a = 'bla 1 bla 2 bla 3' What is the simplest way for me to do this? |
Encrypting and dycrypting input fields before post Posted: 06 Dec 2016 05:42 AM PST I am trying to encrypt input fields on a form, and decrypt them on the controller using RSA, a link to examples with jCryption.js would be appreciated. |
Combining queries into an ActiveRecord_AssociationRelation Posted: 06 Dec 2016 06:10 AM PST Hi I'm working on a project and I need to take result of two database queries and combine them into one ActiveRecord_AssociationRelation, at the moment I have: results.where(pos_or_neg: "neg").order("value DESC") + (results.where(pos_or_neg: "pos").order("value ASC")) However this returns an array which doesn't work as I need to do more processing afterwards. I've tried: results.where(pos_or_neg: "neg").order("value DESC").merge(results.where(pos_or_neg: "pos").order("value ASC")) but this only seems to return the half of the results. Thanks |
ArgumentError: wrong number of arguments (given 0, expected 1..2) Posted: 06 Dec 2016 05:15 AM PST ** Invoke db:migrate:reset (first_time) ** Invoke db:drop (first_time) ** Invoke db:load_config (first_time) ** Execute db:load_config ** Execute db:drop ** Invoke db:create (first_time) ** Invoke db:load_config ** Execute db:create ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment rake aborted! ArgumentError: wrong number of arguments (given 0, expected 1..2) /usr/local/rvm/gems/ruby-2.3.3/gems/activesupport-4.2.5/lib/active_support/cache/file_store.rb:20:in `initialize' /usr/local/rvm/gems/ruby-2.3.3/gems/activesupport-4.2.5/lib/active_support/cache.rb:60:in `new' /usr/local/rvm/gems/ruby-2.3.3/gems/activesupport-4.2.5/lib/active_support/cache.rb:60:in `lookup_store' /usr/local/rvm/gems/ruby-2.3.3/gems/railties-4.2.5/lib/rails/application/bootstrap.rb:76:in `block in <module:Bootstrap>' /usr/local/rvm/gems/ruby-2.3.3/gems/railties-4.2.5/lib/rails/initializable.rb:30:in `instance_exec' /usr/local/rvm/gems/ruby-2.3.3/gems/railties-4.2.5/lib/rails/initializable.rb:30:in `run' /usr/local/rvm/gems/ruby-2.3.3/gems/railties-4.2.5/lib/rails/initializable.rb:55:in `block in run_initializers' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:347:in `each' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:347:in `call' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each' /usr/local/rvm/gems/ruby-2.3.3/gems/railties-4.2.5/lib/rails/initializable.rb:54:in `run_initializers' /usr/local/rvm/gems/ruby-2.3.3/gems/railties-4.2.5/lib/rails/application.rb:352:in `initialize!' /home/ubuntu/workspace/config/environment.rb:5:in `<top (required)>' /usr/local/rvm/gems/ruby-2.3.3/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:274:in `require' /usr/local/rvm/gems/ruby-2.3.3/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:274:in `block in require' /usr/local/rvm/gems/ruby-2.3.3/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:240:in `load_dependency' /usr/local/rvm/gems/ruby-2.3.3/gems/activesupport-4.2.5/lib/active_support/dependencies.rb:274:in `require' /usr/local/rvm/gems/ruby-2.3.3/gems/railties-4.2.5/lib/rails/application.rb:328:in `require_environment!' /usr/local/rvm/gems/ruby-2.3.3/gems/railties-4.2.5/lib/rails/application.rb:457:in `block in run_tasks_blocks' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:248:in `block in execute' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:243:in `each' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:243:in `execute' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:187:in `block in invoke_with_call_chain' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:180:in `invoke_with_call_chain' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:209:in `block in invoke_prerequisites' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:207:in `each' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:207:in `invoke_prerequisites' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:186:in `block in invoke_with_call_chain' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:180:in `invoke_with_call_chain' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:209:in `block in invoke_prerequisites' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:207:in `each' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:207:in `invoke_prerequisites' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:186:in `block in invoke_with_call_chain' /usr/local/rvm/rubies/ruby-2.3.3/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:180:in `invoke_with_call_chain' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/task.rb:173:in `invoke' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/application.rb:152:in `invoke_task' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/application.rb:108:in `block (2 levels) in top_level' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/application.rb:108:in `each' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/application.rb:108:in `block in top_level' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/application.rb:117:in `run_with_threads' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/application.rb:102:in `top_level' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/application.rb:80:in `block in run' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/application.rb:178:in `standard_exception_handling' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/lib/rake/application.rb:77:in `run' /usr/local/rvm/gems/ruby-2.3.3/gems/rake-11.3.0/exe/rake:27:in `<top (required)>' /usr/local/rvm/gems/ruby-2.3.3/bin/rake:22:in `load' /usr/local/rvm/gems/ruby-2.3.3/bin/rake:22:in `<main>' /usr/local/rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `eval' /usr/local/rvm/gems/ruby-2.3.3/bin/ruby_executable_hooks:15:in `<main>' Tasks: TOP => db:migrate:reset => db:migrate => environment I can't find where the error comes from. Please help me. |
Return back dropped(deleted) table Rails Posted: 06 Dec 2016 05:05 AM PST I accidentally deleted table "results" from schema with this command in rails console: ActiveRecord::Migration.drop_table(:results) I tried but not working rake db:migrate:up VERSION=201608021358 How can I take it back? I just want the structure not the data Please help! |
How to create a drop down for parent and child nodes using Ancestry in Rails? Posted: 06 Dec 2016 04:39 AM PST I am new to development environment. I'm am developing an rails application and I am using Ancestry gem for tree structure in rails. After I have created the categories and subcategories in rails. I wanted to display these categories in a dropdown for posts page. But when I tried to display the categories using the following command. <%= f.collection_select :category_id, Category.all, :id, :name, {prompt: "Select a category"}, {class: "form-control"} %> All the categories are showing up. There is no order for these categories in dropdown. But I want a drop down distinguishing parent and child nodes like. -> Root 1 -> Child 1 -> Child 2 -> Root 2 -> Child 1 -> Child 2 Can anyone please help me write the code. |
Method find_by_user_id_and_friend_id does not seem to work - Rails 5 Posted: 06 Dec 2016 06:28 AM PST i am unsure why the method Friendship.find_by_user_id_and_friend_id(user, friend) & Friendship.find_by_user_id_and_friend_id(friend, user) gives a nil, could one kindly explain this to me why does the method Friendship.find_by_user_id_and_friend_id(user, friend) give a nil and the method Friendship.find_by_user_id_and_friend_id(user.id, friend.id) does not? basically could one explain the difference to me 2.3.0 :065 > user => #<User id: 1, email: "richill@gmail.com", created_at: "2016-11-22 15:56:19", updated_at: "2016-12-06 11:39:29", firstname: "richill", lastname: "artloe"> 2.3.0 :068 > friend => #<User id: 2, email: "emma@gmail.com", created_at: "2016-11-22 16:19:25", updated_at: "2016-11-22 16:19:25", firstname: "emma", lastname: "watson"> Friendship.create(user: user, friend: friend, status: 'pending') Friendship.create(user: friend, friend: user, status: 'requested') 2.3.0 :078 > Friendship.find_by_user_id_and_friend_id(user, friend) Friendship Load (0.2ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = ? AND "friendships"."friend_id" = ? LIMIT ? [["user_id", nil], ["friend_id", nil], ["LIMIT", 1]] => nil 2.3.0 :079 > 2.3.0 :079 > Friendship.find_by_user_id_and_friend_id(friend, user) Friendship Load (0.2ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = ? AND "friendships"."friend_id" = ? LIMIT ? [["user_id", nil], ["friend_id", nil], ["LIMIT", 1]] => nil 2.3.0 :080 > i believe i am suppose to get something like the below results: >> Friendship.find_by_user_id_and_friend_id(user, friend) => #<Friendship:0x2bf74ec @attributes={"status"=>"pending", "accepted_at"=>nil, "id"=>"1", "user_id"=>"1", "position"=>nil, "created_at"=>"2007-01-03 18:34:09", "friend_id"=>"1198"}> >> Friendship.find_by_user_id_and_friend_id(friend, user) => #<Friendship:0x490a7a0 @attributes={"status"=>"requested", "accepted_at"=>nil , "id"=>"2", "user_id"=>"1198", "position"=>nil, "created_at"=>"2007-01-03 18:34 :20", "friend_id"=>"1"}> very strange. it works when placed like this Friendship.find_by_user_id_and_friend_id(user.id, friend.id) => #<Friendship id: 1, user_id: 1, friend_id: 2, status: "pending", created_at: "2016-12-06 11:55:06", updated_at: "2016-12-06 11:55:06"> but does not work when placed like this: Friendship.find_by_user_id_and_friend_id(user, friend) => nil could one explain why this is to me what is the difference 2.3.0 :016 > Friendship.find_by_user_id_and_friend_id(user, friend) Friendship Load (0.2ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = ? AND "friendships"."friend_id" = ? LIMIT ? [["user_id", nil], ["friend_id", nil], ["LIMIT", 1]] => nil 2.3.0 :017 > Friendship.find_by_user_id_and_friend_id(user.id, friend.id) Friendship Load (0.2ms) SELECT "friendships".* FROM "friendships" WHERE "friendships"."user_id" = ? AND "friendships"."friend_id" = ? LIMIT ? [["user_id", 1], ["friend_id", 2], ["LIMIT", 1]] => #<Friendship id: 1, user_id: 1, friend_id: 2, status: "pending", created_at: "2016-12-06 11:55:06", updated_at: "2016-12-06 11:55:06"> 2.3.0 :018 > |
Twilio SMS not working with rails 4 Posted: 06 Dec 2016 06:44 AM PST I have followed the instructions at, https://www.twilio.com/blog/2016/04/receive-and-reply-to-sms-in-rails.html, to try and send an SMS in rails 4.0. I have a trial account with a simple Rails controller as follows class MessagesController < ApplicationController skip_before_filter :verify_authenticity_token # skip_before_filter :authenticate_user!, :only => "reply" def reply message_body = params["Body"] from_number = params["From"] boot_twilio sms = @client.messages.create( from: Rails.application.secrets.twilio_number, to: from_number, body: "Hello there, thanks for texting me. Your number is #{from_number}." ) end private def boot_twilio account_sid = Rails.application.secrets.twilio_sid auth_token = Rails.application.secrets.twilio_token @client = Twilio::REST::Client.new account_sid, auth_token end end In MyAppName/config/secrets.yml, I have defined the SID and token. As per the tutorial, I am using ngrok to expose my application to the world. I have entered the URL from ngrok into Twilio's configuration as shown. I have verified the URL ngrok gave me by copying it into browser's URL. When I do, it opens my rails app at the home page. The problem is that Twilio never routes the SMS to my rails app. Rather than responding to the SMS in my reply action, I get "Sent from your Twilio trial account - Hello from Twilio!". This is the Twilio response I got before I even wrote my Rails app. I should mention, I have reply_messages POST /messages/reply(.:format) messages#reply in my routing table |
undefined method empty for nil:nilclass due to no data? Posted: 06 Dec 2016 06:41 AM PST Okay, 1 more then i am hopefully done. I am using Wicked for multi page forms in which i also want to use multiple tables from a mysql database. I created a new step so the user can select a option and fill in some stuff, However, during that stepp i get the following error: Showing /home/supervisor/Rubyrails/Werkvergunning/app/views/enquirys/steps/measurements.html.erb where line #20 raised: <%= collection_select :measurement, :enquiry_measures, measures.select(:measurement).uniq.order('measurement ASC'), :measurement, :measurement, {:prompt => 'kies een maatregel'},{:name => 'select_measurement'} %> undefined method `empty?' for nil:NilClass i suspect that this is because the table is still empty. Am i right? Because i get the same error on the add measurements page, that i want to use to fill that table. The code for the form page used to create the table contents:(this doesnt have the dropdown list as in the other page, uses the same table(measures where the other uses measures trough a join)) <%= form_for @enquiry, method: :put, url: wizard_path do |f| %> <% if f.object.errors.any? %> <div class="error_messages"> <% f.object.errors.full_messages.each do |error| %> <p><%= error %></p> <% end %> </div> <% end %> <fieldset> <legend>Maatregel aanmaken </legend> <%= f.fields_for :measures do |measure| %> <%#measure.fields_for :measure do |measure| %> <div> <%= f.label :measurement %> <%= measure.text_field :measurement %> </div> <div> <%= f.label :type%> <%= measure.text_field :type %> </div> <div> <%= f.label :valid_from%> <%= measure.date_select :valid_from %> </div> <div> <%= f.label :valid_to%> <%= measure.date_select :valid_to %> </div> <div> <%= f.submit 'Next Step' %> <%# knop naar vorige pagina %> <%= button_to "vorige", enquirys_path %> <%# 24-11 MG knop die je terug stuurt naar de homepage %> <%= button_tag "Annuleren", :type => 'button', :class => "subBtn", :onclick => "location.href = '#{root_path()}'" %> </div> </fieldset> <% end %> The steps_controller: class Enquirys::StepsController < ApplicationController include Wicked::Wizard steps *Enquiry.form_steps def show @enquiry = Enquiry.find(params[:enquiry_id]) render_wizard end def update @enquiry = Enquiry.find(params[:enquiry_id]) @enquiry.update(enquiry_params(step)) render_wizard @enquiry end private def enquiry_params(step) permitted_attributes = case step when "basic" [:Reference, :Location, :Description] when "when" [:Amount, :Date] #when "measurements" #[:responsible] when "createmeasures" [:measurement] end params.require(:enquiry).permit(permitted_attributes).merge(form_step: step) end end The database models: Enquiry_measure: class EnquiryMeasure < ActiveRecord::Base belongs_to :enquiry, :class_name => 'Enquiry' #, inverse_of: :enquiry_measures validates_presence_of :enquiry has_many :measure, :class_name => 'Measure' end Measurement has nothing specified in its model. This is the basetable: class Enquiry < ActiveRecord::Base #ophalen van andere tabellen voor het formulier. Has_many is 1 op veel relatie #accepts_nested_attributes Nested attributes allow you to save attributes on associated records through the paren # de dere regel zorgt ervoor dat de maatregelen worden opgehaald via de tussentabel enquiry_measures. # has_many :enquiry_measures, :class_name => 'EnquiryMeasure'#, inverse_of: :Enquiry # accepts_nested_attributes_for :enquiry_measures, :allow_destroy => true # has_many :measures, -> { uniq }, :class_name => 'Measure', :through => :enquiry_measures, dependent: :destroy # 28-11 MG de pagina's die in het form worden gebruikt. cattr_accessor :form_steps do %w(basic when measurements) end attr_accessor :form_step validates :Reference, :Location, presence: true, if: -> { required_for_step?(:basic) } validates :Amount, :Date, presence: true, if: -> { required_for_step?(:when) } #validates :needed, presence: true, if: -> { required_for_step?(:measurements) } def required_for_step?(step) return true if form_step.nil? return true if self.form_steps.index(step.to_s) <= self.form_steps.index(form_step) end end Update After some messing around in the code while i was busy adding some extra (later) needed tables, the error has gone away. However, it does not show any of the fields or labels specified, it is just a empty page with the Maatregelen showing and nothing else. Page nr 3(first 2 pages work, they use 1 table, page 3 and 4 use the other table, later i will add more pages, using even other tables) It all uses the same enquiry and steps controllers. <%= form_for @enquiry, method: :put, url: wizard_path do |f| %> <% if f.object.errors.any? %> <div class="error_messages"> <% f.object.errors.full_messages.each do |error| %> <p><%= error %></p> <% end %> </div> <% end %> <fieldset> <legend>Maatregelen</legend> <%= f.fields_for :enquiry_measures do |enquiry_measures| %> <%= enquiry_measures.fields_for :measure do |measures| %> <div> <%= f.label :Maatregel %> <br /> <%# collection_select(:measure, :enquiry_id, Enquiry.all, :id, :measurement) %> <%# http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select -%> <%= collection_select :measurement, :enquiry_measures, measures.select(:measurement).uniq.order('measurement ASC'), :measurement, :measurement, {:prompt => 'kies een maatregel'},{:name => 'select_measurement'} %> </div> <div> <%= f.label :Gereed %> <br /> <%= enquiry_measures.text_field :done %> </div> <div> <%= f.label :Verantwoordelijke %> <br /> <%= enquiry_measures.text_field :responsible %> </div> <div> <%= f.label :Benodigd %> <br /> <%= enquiry_measures.text_field :needed %> </div> <div> <%= f.submit 'Next Step' %> </div> <% end %> <%# end of enquiry_measures.fields_for :measure %> <% end %> <%# end of f.fields_for :enquiry_measures %> </fieldset> <% end %> |
How can i retrieve uploaded image (base64) full url from Carrierwave upload file to Rackspace? Posted: 06 Dec 2016 04:23 AM PST I just need to get the url of my image (base64) that just uploaded to Rackspace server via Carrierwave. This is my controller now. def update_with_image user = current_user uploader = PictureUploader.new uploader.store!(user_update_params[:profile_image]) // base64 image like this 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2w...' // How can i update user_update_params[:profile_image] with the successfully uploaded profile_image url? if user.update_attributes(user_update_params) # Handle a successful update. render json: user, status: 200 ,serializer: UserSerializer else render json: { errors: user.errors }, status: 422 end end So after uploader.store!(user_update_params[:profile_image]) how can i get the url of that file? Thanks! |
Rails 5 scheduler to update database once a day Posted: 06 Dec 2016 04:15 AM PST I'm new to rails and want to run a batch file/schedule task daily once at midnight that checks which entries have expired. Every record in the table has a closing_date and after that time, such records must be inactive.(status active=false on DB). so basically it will run 2 SQL queries to fetch all records and then flag another field to inactive for records that are outdated.I'm working with Rails 5. How should I go about this-gem(rufus,whatever,clockwork or any other gem) or simply some system tool for cronjob?I'm going to change my DB to PostgreSQL so will that impact? Any suggestions or sample code anyone can share to get an idea. |
How to draw graph for gym "Barbell" according to provided weight [on hold] Posted: 06 Dec 2016 04:05 AM PST I want to draw a graph for gym "Barbell" according to provided weight. e.g: Like above example for 110 kg "Barbell" graph is shown. Please suggest appropriate solutions for this, we can use any technology like PHP, JQUERY, ROR etc. Thanks in Advance. |
Show data from join table ruby on rails Posted: 06 Dec 2016 07:10 AM PST I was trying to show the student name on the submission table but I don't know how to do it. If you can please help me! Form.rb: class Form < ActiveRecord::Base belongs_to :user has_many :submissions, :dependent => :destroy has_attached_file :image, styles: { medium: "400x600>" } validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/ end Submission.rb: class Submission < ActiveRecord::Base belongs_to :form has_many :submissionstudent has_many :students, :through => :submissionstudent end Student.rb: class Student < ActiveRecord::Base has_many :submissionstudent has_many :submissions, :through => :submissionstudent end Joint Table: Submissionstudent: class Submissionstudent < ActiveRecord::Base belongs_to :submission belongs_to :student end Show Table: <h1><%= @form.title %></h1> <p> <%= image_tag @form.image.url(:medium) %> </p> <table class="table table-responsive table-hover"> <% if user_signed_in? %> <% if @submissions.blank? %> <h4>No submission just yet</h4> <% else %> <thead> <th>Conflict</th> <th>Computer</th> <th>Extra time</th> <th>AM or PM</th> </thead> <tbody> <% @submissions.each do |submission| %> <tr> <td><%= submission.conflict %></td> <td><%= submission.computer %></td> <td><%= submission.extra_time %>%</td> <td><%= submission.am_pm %></td> <!-- Need to add Edit, Delete --> </tr> <% end %> </tbody> <% end %> <% end %> </table> <%= link_to 'New Submission', new_form_submission_path(@form) %> <br> <%= link_to 'Edit', edit_form_path(@form) %> | <%= link_to 'Back', forms_path(@form) %> Submission Controller: class SubmissionsController < ApplicationController before_action :set_submission, only: [:show, :edit, :update, :destroy] before_action :set_form # GET /submissions/new def new @submission = Submission.new @all_students = Student.all @submission_student = @submission.submissionstudent.build end # GET /submissions/1/edit def edit end # POST /submissions # POST /submissions.json def create @submission = Submission.new(submission_params) @submission.form_id = @form.id respond_to do |format| if @submission.save format.html { redirect_to @form, notice: 'Submission was successfully created.' } format.json { render :show, status: :created, location: @submission } else format.html { render :new } format.json { render json: @submission.errors, status: :unprocessable_entity } end end end # PATCH/PUT /submissions/1 # PATCH/PUT /submissions/1.json def update respond_to do |format| if @submission.update(submission_params) format.html { redirect_to @submission, notice: 'Submission was successfully updated.' } format.json { render :show, status: :ok, location: @submission } else format.html { render :edit } format.json { render json: @submission.errors, status: :unprocessable_entity } end end end # DELETE /submissions/1 # DELETE /submissions/1.json def destroy @submission.destroy respond_to do |format| format.html { redirect_to submissions_url, notice: 'Submission was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_submission @submission = Submission.find(params[:id]) end def set_form @form = Form.find(params[:form_id]) end # Never trust parameters from the scary internet, only allow the white list through. def submission_params params.require(:submission).permit(:conflict, :computer, :extra_time, :am_pm) end end Form Controller: class FormsController < ApplicationController before_action :set_form, only: [:show, :edit, :update, :destroy] before_action :authenticate_user!, except: [:index, :show] def index @forms = Form.all end def show @submissions = Submission.where(form_id: @form.id).order("conflict DESC") @student = Student.find params[:id] end def new @form = current_user.forms.build end def edit end def create @form = current_user.forms.build(form_params) respond_to do |format| if @form.save format.html { redirect_to @form, notice: 'Form was successfully created.' } format.json { render :show, status: :created, location: @form } else format.html { render :new } format.json { render json: @form.errors, status: :unprocessable_entity } end end end # PATCH/PUT /forms/1 # PATCH/PUT /forms/1.json def update respond_to do |format| if @form.update(form_params) format.html { redirect_to @form, notice: 'Form was successfully updated.' } format.json { render :show, status: :ok, location: @form } else format.html { render :edit } format.json { render json: @form.errors, status: :unprocessable_entity } end end end # DELETE /forms/1 # DELETE /forms/1.json def destroy @form.destroy respond_to do |format| format.html { redirect_to forms_url, notice: 'Form was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_form @form = Form.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def form_params params.require(:form).permit(:title, :image) end end Student Controller: class StudentsController < ApplicationController before_action :set_student, only: [:show, :edit, :update, :destroy] # GET /students # GET /students.json def index @students = Student.all end # GET /students/1 # GET /students/1.json def show end # GET /students/new def new @student = Student.new end # GET /students/1/edit def edit end # POST /students # POST /students.json def create @student = Student.new(student_params) respond_to do |format| if @student.save format.html { redirect_to @student, notice: 'Student was successfully created.' } format.json { render :show, status: :created, location: @student } else format.html { render :new } format.json { render json: @student.errors, status: :unprocessable_entity } end end end # PATCH/PUT /students/1 # PATCH/PUT /students/1.json def update respond_to do |format| if @student.update(student_params) format.html { redirect_to @student, notice: 'Student was successfully updated.' } format.json { render :show, status: :ok, location: @student } else format.html { render :edit } format.json { render json: @student.errors, status: :unprocessable_entity } end end end # DELETE /students/1 # DELETE /students/1.json def destroy @student.destroy respond_to do |format| format.html { redirect_to students_url, notice: 'Student was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_student @student = Student.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def student_params params.require(:student).permit(:name) end end If you need something else just comment and I'll provide it Thanks for your help. |
Insert after every nth comma in a string [duplicate] Posted: 06 Dec 2016 03:18 AM PST This question already has an answer here: I have the following string and array: a = '1, 2, 3, 4, 5, 6, 7, 8' b = ['9', '10', '11', '12'] I need to insert an element of b after every nth comma (2 for this example) into a, resulting in: a = '1, 2, 9, 3, 4, 10, 5, 6, 11, 7, 8, 12' I've been playing around with various forms of scan but can't seem to produce the desired result. Is there an easy way for me to do this? |
Create a Rails 5 app + api, both authenticate-able by 2 different Models? Posted: 06 Dec 2016 03:02 AM PST As implied by question: how do you create a Rails 5 app, that has both web interface and (RESTful) API, with authentication on both channels (token for API)? Any help is greatly appreciated! What I wanna achieve: - Rails 5 application
- 2 authentication models --> Users and ContentCreators
- 2 channels: web interface (with Rails = bin/rails serve) and an API (an angular2 website/hybrid app)
- Users is the authentication model with API, and ContentCreators for web interface
I have tried: - using Devise, where I can allow signed in ContentCreators to create contents, but I cannot integrate any further by exposing APIs. specifically I don't know how to
authenticate_user! through API calls. - since Devise on its own doesn't work, I tried
devise_token_auth , which I don't know if it works (is required) or not, but I also can't get it to work coz I seem to be required to set up my own customised sign-in logic as I cannot use third-party (e.g. Facebook) authentication, provided by OmniAuth - And since that doesn't work, I tried
simple_token_authentication . I followed their steps to setup, but I have no idea how its usage works. How do I tell it where my parameters are (URL or request_body), process my parameters, request tokens? why does it seem to assume I already know how to use it?... Why is the url not Rails-formatted (i.e. user?username=aaa instead of user/aaa/) - grape: first I do not understand the syntax... second I have no idea how to start integrating it with the existing basic rails app I got (that has got Devise handling my backend-web-interace logins...)
- I've tried almost all gems I could find out there, but none seem to work out of the box that offers both API and web interface solution...
Options (as I see it): - Create 2 Rails app with 1 database, run them on localhost:3000 and :3001.
- will it even work?
- is it the most efficient way, are there gems / methods in Devise I haven't figured out yet?
- Remove authentication...
Warning: not a seasoned Rails developer, may need some deeper explanation with less assumption of prior knowledge... ^_^ |
Grape with dynamic route Posted: 06 Dec 2016 02:37 AM PST I have a requirement where user can pass url in this format: http:site.com/[action]/[subject]?[option]=[value] for example all of the below are valid urls: http://example.com/trigger/a/b/c http://example.com/trigger/a http://example.com/trigger/a/b?something=value http://example.com/trigger/any/thing/goes/here I have a grape resource like this: class Test < Grape::API params do optional :option, type: String end get '/trigger/:a/:b/:c' do { type: 'trigger', a: params[:a], b: params[:b], c: params[:c], option: params[:option] } end end So, If I visit http://example.com/1/2/3/option=something then I will get { "type": "trigger", "a": "1", "b": "2", "c": "3", "option": "something" } Expected Behavior: Use should be able to provide anything after /trigger/ http://example.com/any/thing/goes/here/1/2/3?other=value&goes=here Update: I found this solution (How do we identify parameters in a dynamic URL?) for rails route, I want this behavior in grape . thanks |
No comments:
Post a Comment