Wednesday, December 7, 2016

Rails - Issue with permitting params & require | Fixed issues

Rails - Issue with permitting params & require | Fixed issues


Rails - Issue with permitting params & require

Posted: 07 Dec 2016 07:40 AM PST

I'm having an issue with submitting my params,

portrait and portrait_tag are passed through my form and are siblings, how would I go permitting both of these?

Output

{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"", "portrait"=>{"artist_image"= "", @original_filename="rubytraining.jpg", @content_type="image/jpeg"}, "portrait_tag"=>{"tag_ids"=>["", "1", "2", "3", "4"]}, "commit"=>"Save changes", "controller"=>"admin/portraits", "action"=>"update", "id"=>"72"}  

I've tried the following

private  def portrait_params      params.require(:portrait).permit(:id, :artist_image)      params.require(:portrait_tag).permit(:id, :tag => [])  end  

These work separately but overwrite one another when added together

controller

def update          @portrait = Portrait.where(artist_id: 33, id: params[:id]).take          if @portrait.update(portrait_params)            redirect_to :edit_admin_portrait, flash: {notice: "Successfully updated your information"}          else          flash[:system] = @portrait.errors.full_messages          p @portrait.errors.full_messages            render :edit        end        end    private  def portrait_params      params.require(:portrait).permit(:id, :artist_image)      params.require(:portrait_tag).permit(:id, :tag => [])  end  

Rails4 security: Session fixation possible at all using encrypted cookies?

Posted: 07 Dec 2016 07:43 AM PST

After studying the rails guide and some other ressources I'm wondering how a session fixation attack on a user's session can actually happen. At least I'm sceptical it works as simple as depicted here in the guide, where an attacker...

1) ...creates a valid session by logging in

2) ...keeps the session alive

3) ...then forces the user to use his session's id e.g. by using some XSS vulnerability

All fine, but... how would the attacker be able to gather the value of his own session id? By default cookies are encrypted in Rails4+. So what to do as an attacker assuming I do not have access to secret_key_base or whatever is used to generate the encryption and signature keys? From what I understand he cannot tamper with the cookie without invalidating it (signature wrong) so somehow passing a self-created cookie to a possible victim is neither an option.

Is the secu guide kind of not up to date or am I missing a point here? If the latter then...

a) how [as an attacker] can I read encrypted cookie information

b) how does a vulnerability have to look like that allows me [the attacker] to inject that session id into the likewise encrypted cookie on another client? Would that be an XSS attack? The guide states that if an attacker uses code like

<script>document.cookie="_session_id=16d5b78abb28e3d6206b60f22a03c8d9";</script>  

he would be able to fix that session. But again, why would rails reveal it's plain session to the client making it accessible via client-side processed javascript? It does not, which is why all my cookie-values are simple gibberish not being accessible by Javascript (can test that via console).

Thanks for any advice!

How to start Cuttlefish

Posted: 07 Dec 2016 07:33 AM PST

I installed Cuttlefish (www.cuttlefish.io) on a RedHat 4.8.5-4 from the Cuttlefish Git repository. Prerequisite gems were also installed, and Ruby.

Being new to Rails, how to start Cuttlefish?

Rails different sql between scope and explicit join

Posted: 07 Dec 2016 07:32 AM PST

I have models with these associations:

class Event < ActiveRecord::Base    has_many :memberships, dependent: :destroy    has_many :users, through: :memberships  end    class Membership < ActiveRecord::Base    belongs_to :user    belongs_to :event  end  

And following methods:

#In Membership  scope :available_for, -> (user) { joins(:event).merge(Event.available_for(user)) }    #In Event  def self.available_for(user)    ...    joins(:memberships).where('memberships.user_id': user.id).ids    ...  end  

So in controller when I call:

@memberships = @user.memberships.available_for(current_user)  

Apparently is not the same as:

@memberships = @user.memberships.joins(:event).merge(Event.available_for(current_user))  

In first case it works not as expected, it adds extra AND while join in sql:

SELECT "events".id FROM "events" INNER JOIN "memberships" ON "events"."id" = "memberships"."event_id" WHERE "memberships"."user_id" = $1 AND "memberships"."user_id" = $2  

In second it has no AND:

SELECT "events"."id" FROM "events" INNER JOIN "memberships" ON "memberships"."event_id" = "events"."id" WHERE "memberships"."user_id" = $1  

I can't get why this is happening, any guess?

Moreover if I change this:

@memberships = @user.memberships.available_for(current_user)  

To this:

@memberships = Membership.available_for(current_user).where(user_id: 1)  

It will work as expected as I added join explicitly as above

Mantaining an array and some nested form fields consistent?

Posted: 07 Dec 2016 07:24 AM PST

I'm using cocoon to handle some form fields but I need to use the values of the active form fields elsewhere on the page, specifically on an array that is used elsewhere; so I need to populate the form fields with the array and when one changes, change the other.

What I'm currently doing is, whenever the array is modified, I remove all form fields, add them again but then I can't access them by the index and when one is changed I'm unsure how to catch the change and get the actual index modified, given how cocoon handles inserting and deleting, the index isn't consistent with what's shown.

how to cache thumbnails on local filesystem using rails + paperclip + aws-sdk

Posted: 07 Dec 2016 07:23 AM PST

I'm trying Rails + Paperclip to upload files to AWS using aws-sdk gem,

Question: how to keep CACHED :thumb of every file at the local filesystem at my rails server, to minimize requests to AWS when reviewing large amounts of files? (having :thumb cached only at local filesystem or both locally + AWS)

my env is: Rails4. Paperclip latest. Using Paperclip is not obligatory, any workable solution is acceptable.

Kill postgre connection in rails console

Posted: 07 Dec 2016 07:19 AM PST

How can I kill all postgre connections using rails console? I am getting this:

PG::ConnectionBad  FATAL: sorry, too many clients already FATAL: sorry, too many clients already    Rails.root: C:/Users/IBM_ADMIN/Desktop/Work/Extreme Blue Summer Internship/extreme-blue    Application Trace | Framework Trace | Full Trace  activerecord (4.2.7.1) lib/active_record/connection_adapters/postgresql_adapter.rb:651:in `initialize'  activerecord (4.2.7.1) lib/active_record/connection_adapters/postgresql_adapter.rb:651:in `new'  activerecord (4.2.7.1) lib/active_record/connection_adapters/postgresql_adapter.rb:651:in `connect'  activerecord (4.2.7.1) lib/active_record/connection_adapters/pos  

The thing is I don't want to drop the database, but just to kill all the connections to it? Any help will be kindly appreciated!

tgresql_adapter.rb:242:in `initialize'

How to get timezone number from Time.now

Posted: 07 Dec 2016 07:14 AM PST

Time.now   #=> 2007-11-19 08:27:30 -0600  

I want get the number 0600 which is bold. A Native ruby function is welcome if it exist.

What i tried :

Time.now.to_s.byteslice(-3) #=> 6  

It works but I want to find a better way.

Acturely, I'm not sure if i can call it timezone number. Please tell me its name in english. Thank you.

Cucumber and Carrierwave - undefined method 'attachment_changed?'

Posted: 07 Dec 2016 06:53 AM PST

I have a rails 4 app where everything works from the UI, or in the console. When I run the cucumber tests I get this failure:

When I sign in with valid credentials   #  features/step_definitions/user_steps.rb:71        undefined method `attachment_changed?' for #<User:0x007f8ef78cda88>        Did you mean?  attachment_cache                   attachment_cache= (NoMethodError)        ./app/controllers/application_controller.rb:13:in `set_current_user'        ./features/step_definitions/user_steps.rb:43:in `sign_in'        ./features/step_definitions/user_steps.rb:73:in `/^I sign in with valid credentials$/'        features/sign_in.feature:15:in `When I sign in with valid credentials'  

The line in the application_controller is:

User.current_user = current_user unless current_user.nil?  

Here is the user model:

  devise :database_authenticatable, :registerable,       :recoverable, :rememberable, :trackable, :validatable      include Archivable      mount_uploader :attachment, AttachmentUploader      belongs_to :company    after_initialize :set_default_role, :if => :new_record?     def self.current_user      @current_user || User.new(email: 'admin@us.com', first_name: 'admin', last_name: 'User')    end      def self.current_user=(cur_user)      @current_user = cur_user    end  

If I remove the mount_uploader line, everything works fine. If I test with the console, I can see that carrierwave remaps the attachment attribute to a carrierwave object, thus attachment_changed? is nil instead of false. My question is why is the assignment of current_user triggering a whole dirty check of the model? And, how do I suppress it?

Can't see nested fields in view when using accepts_nested_attributes_for method while using Ruby 2.3, Rails 5.0, Windows (32-bit)

Posted: 07 Dec 2016 06:49 AM PST

I'm trying to build a workout application where you submit a workout that consists of several exercises in rails. I was trying to create a "new" workout view where you can submit a new workout along with nested exercises but my "new" view is only showing the workout form fields, but not the exercise form fields. Btw I'm using Ruby 2.3 and Rails 5.0. Can anyone see what I'm doing wrong?

Workout Model (workout.rb)

class Workout < ActiveRecord::Base      has_many :exercises, :dependent => :destroy      accepts_nested_attributes_for :exercises  end  

Exercise Model (exercise.rb)

class Exercise < ActiveRecord::Base      belongs_to :workout  end  

Workouts Controller (workouts_controller.rb)

class WorkoutsController < ApplicationController      def new          @workout = Workout.new          @workout.exercises.build      end  end  

New Workout View (views\workouts\new.html.erb)

<h1>Create New Workout</h1>    <%= form_for(@workout) do |f| %>    <%= f.number_field :workout_length, :placeholder => "Workout length   (minutes)" %> <br>    <%= f.text_field :workout_description, :placeholder => "Workout description" %> <br>    <% f.fields_for :exercises do |builder| %>  <p>      <%= builder.text_field :exercise_description %>  </p>  <% end %>    <%= f.submit "SUBMIT WORKOUT" %>  

Schema (schema.rb)

ActiveRecord::Schema.define(version: 20161207040053) do    create_table "exercises", force: :cascade do |t|      t.string   "exercise_description"      t.integer  "workout_id"      t.datetime "created_at",           null: false      t.datetime "updated_at",           null: false      t.index ["workout_id"], name: "index_exercises_on_workout_id"    end      create_table "workouts", force: :cascade do |t|      t.integer  "workout_length"      t.string   "workout_description"      t.datetime "created_at",          null: false      t.datetime "updated_at",          null: false    end  end  

Language Redirect 300 without "You are being redirected"

Posted: 07 Dec 2016 06:41 AM PST

I've found many questions and answers in stack about my problem but they just say that I need to change redirect status to 301 or anything else.

But I need to make redirect if cookies[:lang].nil? with status 300 for correct work with search engines. I've fount that I can add meta like

%meta(http-equiv="refresh" content="0;/ru")  

But it waits full loading page and then make redirect. It's awful decision.

It works fine except of Google Chrome browser. (maybe all webkit) How can I solve my problem?

I'm using rails 4, refinerycms 3.

Make redirect like:

url, is_redirect = set_current_lang if cookies[:lang].nil?  redirect_to url, status: 300 and return if is_redirect and request.path == '/'  

Does ActiveRecord make a new database connection per model

Posted: 07 Dec 2016 07:06 AM PST

I'm trying to understand how ActiveRecord connects to a database on a per model basis. So lets assume we have 2 models and one database. When you do a simple Model.find on both models does this create a new database connection for each model so it has its own defined connection or is there a single connection to the database that has been initialised that is shared across the 2 models. Does anyone know where it's doing this in the code?

I am trying to understand how ActiveRecord achieves this.

Rails display routes helper prefix

Posted: 07 Dec 2016 07:09 AM PST

I'm trying to get the route prefix for the current page that a rails application is on. I know that you can get the controller & action info, and you can also get the path with:

request.env['PATH_INFO']  

But there doesn't seem to be an environment variable for the prefix, that or i've missed it somewhere along the line. Is this possible, or do you have to find it through some hacky way using the controller & action / route?

it's almost as if i'm after a:

request.env['PATH_PREFIX']  

or a:

get_prefix(controller_name, action_name)  

SOLVED (In slim):

- Rails.application.routes.router.recognize(request) do |route, matches, param|    => route.name  

Rails 4 - Join Query matches all in array

Posted: 07 Dec 2016 07:01 AM PST

I have two models, Facility and Category:

class Facility < ActiveRecord::Base    has_and_belongs_to_many :categories  end    class Category < ActiveRecord::Base    has_and_belongs_to_many :facilities  end  

Say I have three possible Category records, with name: "Category A", "Category B", and "Category C".

I want to get all Facility records which are in both "Category A" and "Category B".

My latest query is:

Facility.joins(:categories).merge(Category.where(Category.arel_table[:name].matches_all(["Category A", "Category B"])))  

which produces the following SQL:

SELECT "facilities".* FROM "facilities" INNER JOIN "categories_facilities" ON "categories_facilities"."facility_id" = "facilities"."id" INNER JOIN "categories" ON "categories"."id" = "categories_facilities"."category_id" WHERE ("categories"."name" ILIKE 'Category A' AND "categories"."name" ILIKE 'Category B')  

This returns no results.

Using pure Ruby (e.g. Facility.all.select ...), I know there is at least one Facility in the database which belongs to both and only both "Category A" and "Category B".

How can I perform this query either in Rails or using arel?

Jruby Rails: Java::JavaLang::OutOfMemoryError: Java heap space error while compiling assets

Posted: 07 Dec 2016 06:08 AM PST

I am on jruby and rails. i am trying to precompile my assets but its giving me below error.

rake aborted!  Java::JavaLang::OutOfMemoryError: Java heap space  org.mozilla.javascript.ScriptableObject.createSlot(org/mozilla/javascript/ScriptableObject.java:2913)  org.mozilla.javascript.ScriptableObject.getSlot(org/mozilla/javascript/ScriptableObject.java:2841)  org.mozilla.javascript.ScriptableObject.putImpl(org/mozilla/javascript/ScriptableObject.java:2725)  org.mozilla.javascript.ScriptableObject.put(org/mozilla/javascript/ScriptableObject.java:515)  org.mozilla.javascript.IdScriptableObject.put(org/mozilla/javascript/IdScriptableObject.java:386)  org.mozilla.javascript.ScriptableObject.putProperty(org/mozilla/javascript/ScriptableObject.java:2432)  org.mozilla.javascript.ScriptRuntime.setObjectProp(org/mozilla/javascript/ScriptRuntime.java:1665)  org.mozilla.javascript.ScriptRuntime.setObjectProp(org/mozilla/javascript/ScriptRuntime.java:1659)  org.mozilla.javascript.Interpreter.interpretLoop(org/mozilla/javascript/Interpreter.java:1250)  org.mozilla.javascript.Interpreter.interpret(org/mozilla/javascript/Interpreter.java:815)  org.mozilla.javascript.InterpretedFunction.call(org/mozilla/javascript/InterpretedFunction.java:109)  org.mozilla.javascript.ContextFactory.doTopCall(org/mozilla/javascript/ContextFactory.java:393)  org.mozilla.javascript.ScriptRuntime.doTopCall(org/mozilla/javascript/ScriptRuntime.java:3280)  org.mozilla.javascript.InterpretedFunction.call(org/mozilla/javascript/InterpretedFunction.java:107)  RUBY.call(C:/jruby-1.7.16/lib/ruby/gems/shared/gems/therubyrhino-2.0.4/lib/rhino/rhino_ext.rb:193)  Tasks: TOP => assets:precompile  (See full trace by running task with --trace)  

i have tried below command that i found on stakoveflow while searching for this error but still its not working.

rake assets:precompile RAILS_ENV=production EXECJS_RUNTIME='Node' JRUBY_OPTS="-J-d32 -X-C"  

How to overcome this problem?

How do I only let a certain username views messages on my website in Ruby on Rails?

Posted: 07 Dec 2016 06:30 AM PST

I created a model under:

rails generate model user name email password_digest  

My UsersController allows a username to be created:

class UsersController < ApplicationController      def new    end      def create      user = User.new(user_params)      if user.save        session[:user_id] = user.id        redirect_to '/'      else        redirect_to '/signup'      end    end    private      def user_params      params.require(:user).permit(:name, :email, :password, :password_confirmation)    end  end  

I can allow any user that is logged in to view a message but I was wondering how to specify which users. How can I make a name called "Admin" only be able to view the message?

<% if current_user %>    Signed in as <%= current_user.name %> | <%= link_to "Logout", '/logout' %>  <% else %>    <%= link_to 'Login', '/login' %> | <%= link_to 'Signup', '/signup' %>  <% end %>  

Invalid time zone, using gem barometer

Posted: 07 Dec 2016 06:07 AM PST

In my app I want to use gem 'barometer' https://github.com/attack/barometer. Doing in rails console:

barometer = Barometer.new('Paris')  weather = barometer.measure    puts weather.current.temperature  

works fine. But when I replace barometer = Barometer.new('Paris') to barometer = Barometer.new('Cherkasy') and then do: weather = barometer.measure, I get an error: ArgumentError: invalid time zone.

How can I resolve this issue? I tried to set current time zone, but it didn't help. Thanks ahead.

issue with routing & action in controller - Rails 5

Posted: 07 Dec 2016 06:50 AM PST

i get the below error related to the links accept & decline in my views - it's a routing issue but i am unsure how to go about it. could one kindly advise me on how to correct this

error message

No route matches {:action=>"accept", :controller=>"friendships", :id=>"emma"}    No route matches {:action=>"decline", :controller=>"friendships", :id=>"emma"}  

views/users/_friends.html.erb

<% @user.requested_friends.each do |requester| %>    <tr>      <td><%= link_to(image_tag("img-profile-image-default.png"), requester) %></td>       <td><%= link_to requester.firstname, requester %></td>      <td>        <%= link_to "Accept",                    { controller: "friendships",                       action: "accept",                      id: requester.firstname } %>        <%= link_to "Decline",                    { controller: "friendships",                       action: "decline",                      id: requester.firstname },                      confirm: "Really decline friendship with #{requester.firstname}?" %>      </td>     </tr>  <% end %>  

friendships_controller.rb

class FriendshipsController < ApplicationController    before_filter :setup_friends      def create      Friendship.request(@user, @friend)      flash[:notice] = "Friend request sent."      redirect_to :back    end      def accept      if @user.requested_friends.include?(@friend)        Friendship.accept(@user, @friend)        flash[:notice] = "Friendship with #{@friend.firstname} accepted!"      else        flash[:notice] = "No friendship request from #{@friend.firstname}."      end      redirect_to :back    end      def decline      if @user.requested_friends.include?(@friend)        Friendship.breakup(@user, @friend)        flash[:notice] = "Friendship with #{@friend.firstname} declined"      else        flash[:notice] = "No friendship request from #{@friend.firstname}."      end      redirect_to :back    end      def delete      if @user.friends.include?(@friend)        Friendship.breakup(@user, @friend)        flash[:notice] = "Friendship with #{@friend.firstname} deleted!"      else        flash[:notice] = "You aren't friends with #{@friend.firstname}"      end      redirect_to :back    end      private    def setup_friends      @user = User.find(current_user.id)      @friend = User.find_by_email(params[:id])    end  end  

routes file

Rails.application.routes.draw do    resources :friendships, only: [:create, :update, :destroy]  end                   friendships POST   /friendships(.:format)         friendships#create                friendship PATCH  /friendships/:id(.:format)     friendships#update                           PUT    /friendships/:id(.:format)     friendships#update                           DELETE /friendships/:id(.:format)     friendships#destroy  

Is there any better gem for rails 5 which can create a contact us page for my website?

Posted: 07 Dec 2016 06:21 AM PST

I already knew about contact_us gem. Any other option better than this is required and little help too.

Multiple Memcache Implementation in Rails

Posted: 07 Dec 2016 06:03 AM PST

How to use multiple cache in Rails. config.cache_store = :dalli_store, memcached_server By adding this in application.rb ,when I do Rails.cache.read will be reading from above cache. But how to add once more cache and fetch ?

Rails sending null parameter in post

Posted: 07 Dec 2016 06:20 AM PST

I created a migration to add a new boolean value to my form, but when i send the form the hash value send a null value for my new field. I made the migration like i made the others boolean fiels. Can someone help me in this?

This is the result hash.

Parameters: {"utf8"=>"✓", "authenticity_token"=>"gMxerNn+jYk39ADC1EfIio6fqsfdcvtfnlkUOK7WNgmZrIyzRh2VsxBF9E9fAfT0W3oiHX2UYhYJ+MtfnHxtBg==", "campanha"=>{"titulo"=>"Teste App", "data_termino_venda"=>"22/12/2016 14:19", "data_limite_boleto"=>"22/12/2016 14:19", "suporte_versao_app"=>"1.0", "meio_pagamento"=>"iugu", "enviar_voucher"=>"1", "enviar_sms"=>"0", "enviar_push_notification"=>"1", "salvar_endereco"=>"0", "auto_accepts_solicitation"=>"", "nome_moeda"=>"Coins", "pedido_emitido_instrucoes"=>"<ul><li>1</li><li>d</li><li>sas</li><li>ads</li><li>dsa</li><li>sd</li><li>as</li><li>dsa</li><li>das</li><li>a</li></ul><p><br></p>", "titulo_voucher1"=>"juquinha", "descricao_voucher1"=>"<div><b>olea uhaeus hueau usahue a</b></div><div><b>euahush usah&nbsp;</b></div><div><b>euauseuhas</b></div><div><b><br></b></div><div><br></div><div><b>Ut sumo virtute vim, cum vide definitionem eu. Ex agam velit eam, nam antiopam mediocrem an, mei everti iudicabit voluptatibus ea. Audire aliquando ex quo, id has vidit nonumy gloriatur, tollit persius vituperata at vel. Mollis reprimique eu nec. Sea prima labores at, mei magna detracto in, nam deserunt philosophia te. Ex nec decore honestatis omittantur.</b></div>", "titulo_voucher2"=>"juquinha", "descricao_voucher2"=>"<h3 style=\"margin: 15px 0px; padding: 0px; font-weight: 700; font-size: 14px; color: rgb(0, 0, 0); font-family: &quot;Open Sans&quot;, Arial, sans-serif;\">Seção 1.10.32 de \"de Finibus Bonorum et Malorum\", escrita por Cícero em 45 AC</h3><p style=\"margin-bottom: 15px; padding: 0px; text-align: justify; color: rgb(0, 0, 0); font-family: &quot;Open Sans&quot;, Arial, sans-serif; font-size: 14px;\">\"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?\"</p>"}, "files"=>"", "commit"=>"Salvar", "id"=>"teste-app"}  

This is my view field.

  <div class="form-group">  <%= f.label 'AtivarSolicitação automática de ingresso' %><br>  <%= f.check_box :auto_accepts_solicitation, class: 'input-switch bootstrap-switch-primary' %>  

Merge subarrays into single one and remove duplicates if they have same id using ruby on rails

Posted: 07 Dec 2016 07:15 AM PST

I have an array of arrays like this:

array = [[1, 'Something', '123456321'], [2, 'Something', '123456321'], [2, 'Something', '1234563212']]  

And I want to merge the subarrays that have same id and get this result:

array = [[1, 'Something', '123456321'], [2, 'Something, Something', '123456321, 1234563212']]  

Can anyone help me? Thanks!

Ruby download objects from html url

Posted: 07 Dec 2016 05:56 AM PST

I'm new to RoR.

I'm creating a small app that uploads, deletes and downloads mp3 objects from an s3 bucket. (using aws-sdk gem).

I can't manage to create the right download controller.

All help will be appreciated!

This is my code:

controller >

  def download      bucket = S3.bucket(S3_BUCKET.name)      obj = bucket.object(params[:song])      byebug      send_data obj    end  

view >

<%= link_to "download", "songs/download/?song=" + song.name %>  

And the response from byebug:

(byebug) send_data obj    Rendering text template    Rendered text template (0.0ms)  Sent data  (2.2ms)  "#<Aws::S3::Object:0x007fc3b1323c60>"  (byebug)   

My app is downloading a text file called download with the Object reference from s3 ( Aws::S3::Object:0x007feb59782368 ).

Rails 5 - first vs where limit 1 vs find

Posted: 07 Dec 2016 05:58 AM PST

Using Benchmark ips I did this testing. Correct me if I'm wrong in what I just tested. Note that 96 is the id of the first user in my db.

Benchmark.ips do |x|    x.report("first") do      User.first    end    x.report("where") do      User.where(id: 96).limit(1)    end    x.report("find") do      User.find(96)    end    x.compare!  end  

I ran this test several times and got this as result

Comparison:                 where:    26430.8 i/s                 first:      999.8 i/s - 26.44x  slower                  find:      964.3 i/s - 27.41x  slower  

My conclussion of this is to always use where instead of find or first as these are much slower ways to get a specific user.

Rails 5.0.0.1, PostgreSQL 9.5.3, Ruby 2.3.1

What is a good way to store global site settings in Rails that are editable by an admin?

Posted: 07 Dec 2016 05:46 AM PST

I'm working on a rails portfolio application which only has an admin(s) to manage the site. The admin should for example be able to change the site name or the header image. What is a good way to implement this?

Change navbar color when resized [duplicate]

Posted: 07 Dec 2016 05:04 AM PST

This question already has an answer here:

Hello I am using bootstrap on my rails app and I need to have a transparent navbar. But when it resizes, the transparency make it ugly... I would need to add a background to my navbar (when resized only) but I don't find out how...

screenshot

_nav.html.slim

.nav.navbar.navbar-fixed-top    .container-fluid      .navbar-header        button.navbar-toggle.collapsed[type="button" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"]          span.sr-only            | Toggle navigation          span.icon-bar          span.icon-bar          span.icon-bar        .navbar-brand.leschner-brand          = link_to "LESCHNER", root_path        #bs-example-navbar-collapse-1.collapse.navbar-collapse        ul.nav.navbar-nav.navbar-right          li            = link_to "About", page_path("about")          li            =link_to "Work In Progress", progresses_path          li            =link_to "Finished Guitars", guitars_path          li            =link_to "Media", page_path('media')            li.dropdown            a.dropdown-toggle[href="#" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"]              | Contacts              span.caret            ul.dropdown-menu              li                = link_to "Contact Luthier", new_contact_path(@contact)              li                = link_to "Report a bug", new_support_path(@support)  

the corresponding sass .nav

  //background-color: #75521a    background-color       : rgba(0, 0, 0, 0)    a      color                : #ffffff      a:hover      background-color     : rgba(0, 0, 0, 0) !important      border-bottom        : 4px solid  #AB813E !important      padding-bottom       : 0    .navbar-nav > li > .dropdown-menu    background-color        : #75521a    a:hover      background-color      : #AB813E !important      .nav .open > a, .nav .open > a:hover, .nav .open > a:focus    background-color        : #AB813E !important    .icon-bar    background-color        : #ffffff    .leschner-brand    color                    : #FFFFFF !important    font-family              : 'leschnerfont'    a:hover      background-color       : #75521a !important      color                  : #ffffff      text-decoration        : none    a:visited      color                  : #ffffff  

how to integrate the alfersco with already existing rails application?

Posted: 07 Dec 2016 04:59 AM PST

I will try to integrate my application with alfersco for use some functionalities like documentation .. from alfersco to my rails application.

Rails time_zone_select to use "official" time zone values

Posted: 07 Dec 2016 04:51 AM PST

My view (haml):

= f.time_zone_select :time_zone, nil, {}, class: 'form-control'  

Renders to:

...  <option value="Ljubljana">(GMT+01:00) Ljubljana</option>  <option value="Madrid">(GMT+01:00) Madrid</option>  <option value="Paris">(GMT+01:00) Paris</option>  <option value="Prague">(GMT+01:00) Prague</option>  ...  

When creating a record I want to set the :time_zone attribute to the current time zone of the user. There are several ways to do this but after researching I found either the gem timezone_local or the JS library jstz most common ones. Either way, all those open source libraries seem to use a different pattern then rails does, e.g the Paris timezone is defined as:

Europe/Paris

However, the TimeZone object in Rails uses

Paris

this leads to inconsistencies when I want to create a record with the current time zone of the user as it won't match. I need rails to use the same patterns as jstz or vice versa but I don't want to gsub strings here or similiar. What is the best approach here?

Rails 4; Stub implementation

Posted: 07 Dec 2016 05:22 AM PST

Here I'd love to stub some implementation. This is an original one.

ActiveRecord::Base.transaction do    itemable = create_invoiceitemable(each_line)    next unless itemable.present?      create_invoiceitem(invoice, itemable, each_line[:id])  end  ReceiptMailer.receipt(invoie[:uuid]).deliver_later  

config/initializers/stubs.rb

ReceiptMailer.prepend(Module.new do    def receipt(*args)      Logger.info "ReceiptMailer#receipt called with #{args.inspect}"      Hashie::Mash.new { deliver_later: nil } # to allow call    end  end) unless RAILS_ENV[:production]  

However deliver_later can not be stubbed somehow, instead it starts looking for Redis connection. (deliver_now with the above way just works perfectly.)

Any ideas to work around the Redis connection with those stubbing.

Show student_name on submission show table rails

Posted: 07 Dec 2016 06:32 AM PST

I need to show the student name that I selected in the submission form through a dropdown in my show submission table.

show submission:

<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>            <td><%= submission.student.id %></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 %>  

submission form:

<%= form_for([@form, @submission]) do |f| %>  <% if @submission.errors.any? %>      <div id="error_explanation">        <h2><%= pluralize(@submission.errors.count, "error") %> prohibited this submission from being saved:</h2>          <ul>          <% @submission.errors.full_messages.each do |message| %>            <li><%= message %></li>          <% end %>        </ul>      </div>    <% end %>      <div class="field">      <%= f.label :conflict %><br />      <%= f.radio_button :conflict, :Yes, required: :true %> Yes<br>      <%= f.radio_button :conflict, :No, required: :true %> No    </div>    <br>    <div class="field">      <%= f.label :computer %><br />      <%= f.radio_button :computer, :Yes, required: :true %> Yes<br>      <%= f.radio_button :computer, :No, required: :true %> No    </div>    <br>    <div class="field">      <%= f.label :am_pm %><br />      <%= f.radio_button :am_pm, :Am, required: :true %> Am<br>      <%= f.radio_button :am_pm, :Pm, required: :true %> Pm    </div>    <br>    <div class="field">      <%= f.label "Student" %><br />      <%= collection_select(:student, :student_id, Student.all, :id, :student_name, prompt: true) %>    </div>    <br>    <div class="field">      <%= f.label :extra_time %><br />      <%= f.radio_button :extra_time, 25, required: :true %> 25%<br>      <%= f.radio_button :extra_time, 50, required: :true %> 50%    </div>    <br>    <div class="actions">      <%= f.submit "Submit", class: "btn btn-primary" %>    </div>  <% 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    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  

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(:student_name)      end  end  

submission.rb:

class Submission < ActiveRecord::Base    belongs_to :form    has_one :student  end  

student.rb:

class Student < ActiveRecord::Base    belongs_to :submission  end  

The problem is that if I try to see the last submission in the console, there is nothing that correlates to the username I chose.

Thanks

No comments:

Post a Comment