Friday, July 1, 2016

routing error for nested resource with ledermann-rails-settings | Fixed issues

routing error for nested resource with ledermann-rails-settings | Fixed issues


routing error for nested resource with ledermann-rails-settings

Posted: 01 Jul 2016 08:22 AM PDT

I'm trying to allow users to update preferences from default settings with a form for ledermann-rails-settings. I got the form built based on this answer, but when I try to submit the form to update settings, I get a routing error that I think is related to nested resources, but I'm new to RoR so I'm not sure. Other questions about this on SO appear to use Rails 3 or a previous version of the gem. I'm using rails 4.2.1.

routes.rb:

resources :users do    resources :settings  end  

rake routes:

      user_settings GET    /users/:user_id/settings(.:format)          settings#index                      POST   /users/:user_id/settings(.:format)          settings#create     new_user_setting GET    /users/:user_id/settings/new(.:format)      settings#new    edit_user_setting GET    /users/:user_id/settings/:id/edit(.:format) settings#edit         user_setting GET    /users/:user_id/settings/:id(.:format)      settings#show                      PATCH  /users/:user_id/settings/:id(.:format)      settings#update                      PUT    /users/:user_id/settings/:id(.:format)      settings#update                      DELETE /users/:user_id/settings/:id(.:format)      settings#destroy                users GET    /users(.:format)                            users#index                      POST   /users(.:format)                            users#create             new_user GET    /users/new(.:format)                        users#new            edit_user GET    /users/:id/edit(.:format)                   users#edit                 user GET    /users/:id(.:format)                        users#show                      PATCH  /users/:id(.:format)                        users#update                      PUT    /users/:id(.:format)                        users#update                      DELETE /users/:id(.:format)                        users#destroy  

the form:

<%= form_for(:settings) do |form| %>  <h3>Dashboard settings</h3>    <%= form.fields_for :dashboard, current_user.settings(:dashboard) do |f| %>        <%= f.label :theme_light, 'Light (Default)' %>        <%= f.radio_button :theme, "themes/flatly" %>        <%= f.label :theme_dark, 'Dark' %>        <%= f.radio_button :theme, "themes/darkly" %>    <% end %>    <%= form.submit "Save" %>  <% end %>  

SettingsController:

class SettingsController < ApplicationController    def update      if params[:settings]        params[:settings].each do |key, value|          current_user.settings(key.to_sym).update_attributes! value        end        flash[:success] = "Settings updated!"        redirect_to root_path      else        render 'edit'      end    end  end  

User.rb:

has_settings do |s|    s.key :dashboard, :defaults => { :theme => 'themes/flatly' }  end  

Submitting the form as-is right now gives the following routing error:

Started POST "/users/1/settings/1/edit" for 72.231.138.82 at 2016-07-01 15:12:36 +0000 ActionController::RoutingError (No route matches [POST] "/users/1/settings/1/edit")

I think I understand the Rails Guides for nested resource forms to mean that the first line of the form should be something like

<%= form_for([@user, @settings]) do |form| %>  

but changing that gives the error

First argument in form cannot contain nil or be empty

Additionally, ledermann-rails-settings doesn't appear to have a method for calling all settings (at least so far as I can tell on the current version of the gem), so I'm not sure how I would even define @settings.

I've tried specifying different paths in the form with no luck, as well as trying resource: setting and resources: settings in routes.rb. I feel like I'm missing something at either the controller or routes level, but I don't have enough experience to know where and the gem docs and issues don't have much on forms.

Rails Dynamically return today's date at runtime

Posted: 01 Jul 2016 08:18 AM PDT

For demonstration purposes: say I am including in the module TodayDynamicDate into the model Foo below:

# app/models/concerns/today_dynamic_date.rb  module TodayDynamicDate    extend ActiveSupport::Concern      def todays_date      Date.today    end  end    #app/models/foo.rb  class Foo < ApplicationRecord    include TodayDynamicDate  end  

I am wondering if using that mixed in method of #todays_date will work how I want it to.

I want the method #todays_date to dynamically return the date that the method was run. I do not want it to return the static date that the rails server was booted up.

Example:

Say I boot up the server today, Friday, July 1st, 2016. Here is what I expect the method to return today:

Foo.new.todays_date    => Fri, 01, Jul 2016  

The server continues running and it is now Tuesday, July 5th, 2016. That same method is called in the app and here is what I expect it to return:

# dynamically returning the date that the method was called  Foo.new.todays_date    => Tues, 05, July 2016  

I want to ensure that it will not return this:

# returning a static date  Foo.new.todays_date    => Fri, 01, Jul 2016  

Question: Will my implementation return a dynamic date? If it will not return a dynamic date: how would I do that with that mixed-in method todays_date?

Ruby on Rails: Call Model method in view

Posted: 01 Jul 2016 08:28 AM PDT

I am trying to achieve Paypal integration with rails. Following this (http://railscasts.com/episodes/141-paypal-basics) I have a function in model which call paypal service with a return url. I have added a link in view that links to method in model.But some how rails is not able to get function in model.

What am i doing wrong?

My View :

form_for @order do |f|  - if @order.errors.any?      #error_explanation          h2 = "#{pluralize(@order.errors.count, "error")} prohibited this order from being saved:"          ul              - @order.errors.full_messages.each do |message|                  li = message  .field      = f.label :first_name      = f.text_field :first_name  .field      = f.label :last_name      = f.text_field :last_name  .field      = f.label :card_number      = f.text_field :card_number  .field      = f.label :card_verification, "Card Verification Value (CVV)"      = f.text_field :card_verification  .field      = f.label :card_expires_on      = f.date_select :card_expires_on, {start_year: Date.today.year, end_year: (Date.today.year+10), add_month_numbers: true, discard_day: true}, {class: "browser-default"}  .field      = link_to 'PayPal', @order.paypal_url(current_user)<= link to model function   .actions      = f.submit  

My Model : defined following function.

def paypal_url(return_url)  values = {    :business => 'xxxxx.XXXXX@techflex.com',    :cmd => '_cart',    :upload => 1,    :return => return_url,    :invoice => id  }    values.merge!({    "amount_#{1}" => item.unit_price,    "item_name_#{1}" => item.product.name,    "item_number_#{1}" => item.id,    "quantity_#{1}" => item.quantity  })    "https://www.sandbox.paypal.com/cgi-bin/webscr?" + values.to_query  

end

Error :

NoMethodError in Orders#new  Showing C:/Users/Suniljadhav/SourceCode/TrainStation/app/views/orders/_form.html.slim where line #24 raised:    private method `paypal_url' called for #<Order:0x5e49bf8>  Trace of template inclusion: app/views/orders/new.html.slim  

Rails.root: C:/Users/Suniljadhav/Source Code/TrainStation

Overwriting sqlite database - rails

Posted: 01 Jul 2016 08:13 AM PDT

I have created a model for an app. I'm trying to overwrite the existing database (blank) with another that has some information. When I look into the database, there are several items. However when I try to load those in a page I get an error saying - there are pending migrations, run db:migrate. After doing that the entire database is wiped out and replace by a blank database. Can someone help me out with this?

Ruby TZInfo and Rails ActiveSupport::Timezone UTC_offset differences

Posted: 01 Jul 2016 08:15 AM PDT

I want to find the total UTC offset from a Timezone Object. Below are two examples using TZInfo::Timezone and ActiveSupport::TimeZone. Ultimately, I want to use the ActiveSupport::TimeZone implementation, but can't get it to give me the right answer.

#TZInfo implementation  tz = TZInfo::Timezone.get('America/New_York')  tz.current_period.utc_total_offset / 60 / 60  => -4 (CORRECT)    # Rails implementation  tz = ActiveSupport::TimeZone.new("Eastern Time (US & Canada)")  tz.utc_offset / 60 / 60  => -5 (WRONG)  

Why does ActiveSupport::TimeZone appear to fail to factor in dst? How do I fix that?

How to create a form that will create a tree of anwers and questions

Posted: 01 Jul 2016 07:48 AM PDT

I am trying to build a form in my rails app that will generate a tree of answers and questions.The form will be asking the users for the different questions and answers in order to build the tree. On the first node of the tree, there is a question. This question has_many potential answers. Then on the next nodes, if the branch is finished there is just a final answer. Otherwise there is an answer and a new question linked to this answer that in turn might have several answers. So I have answer has_one question

I am a bit lost on how to build that form. I believe I should get a JSON that looks something like that when the form is submitted :

{ question: description: "qui a tué henri ?", answer: { content: "Jacques", question: { description: "Pourquoi Jacques aurait il fait ça?", answer:{ content: "il ne l'aimait pas", question:{ description: "Pourquoi il ne l'aimait pas", answer:{ content: "c'est fini" } } } answer: { content: "parceque jacques était le cousin de paul", question:{ description: "Que se passe t'il ?", answer:{ content: "rien" } } } } } answer: { content: "Paul", question: { description: "Pourquoi Paul aurait il fait ça?", answer: { content: "Parcequ'il voulait son argent?" } } } }

Here we have a tree with the initial question "qui a tué henri" that has two possible answers "Jacques" and "Paul" that in turn each have one question....

I have thought about something like:

  <%= label_tag :content, "Type your first question" %>    <%= text_area_tag "question[1][content]" %>      <%= label_tag :description, "Type answer 1 related to question 1" %>    <%= text_area_tag "question[1][answer][1][description]" %>      <%= label_tag :content, "Type your question related to answer 1" %>    <%= text_area_tag "question[1]answer[1]question[content]" %>      <%= label_tag :description, "Type answer 2 related to question 1" %>    <%= text_area_tag "[question][1][answer][2][description]" %>      <%= label_tag :content, "Type your question related to answer 2" %>    <%= text_area_tag "question[1][answer][2][question][3][content]" %>  

Of course it will then be necessary to have JS that dynamically inserts and removes inputs to the form to be able to add infinitely nodes of answers and questions but I put that appart for now and am just trying to understand the basic logic on how to build such a form.

What would be the correct way to write an html form that will enable to build such a tree structure ?

Rails Tutorial static pages routes test red (5.28)

Posted: 01 Jul 2016 07:51 AM PDT

Doing Michael Hartl's Rails Tutorial, but stumped on Listing 5.28 (getting RED test instead of GREEN), changing the test to match the new routes.

ERRORS for all pages (/, /about, /contact, /help):

ActionController::UrlGenerationError: No route matches {:action=>"/*", :controller=>"static_pages"}  

routes.rb

Rails.application.routes.draw do    root 'static_pages#home'    get  '/help',    to: 'static_pages#help'    get  '/about',   to: 'static_pages#about'    get  '/contact', to: 'static_pages#contact'  end  

tests/controllers/static_pages_controller_test.rb

require 'test_helper'    class StaticPagesControllerTest < ActionController::TestCase    test "should get home" do      get root_path      assert_response :success      assert_select "title", "Ruby on Rails Tutorial Sample App"    end      test "should get help" do      get help_path      assert_response :success      assert_select "title", "Help | Ruby on Rails Tutorial Sample App"    end      test "should get about" do      get about_path      assert_response :success      assert_select "title", "About | Ruby on Rails Tutorial Sample App"    end      test "should get contact" do      get contact_path      assert_response :success      assert_select "title", "Contact | Ruby on Rails Tutorial Sample App"    end    end  

static_pages_controller.rb

class StaticPagesController < ApplicationController    def home    end      def help    end      def about    end      def contact    end    end  

Let me know if you need to see any other code! Have tried adding as: '*' after each get route, but to no avail.

Not sure if it is a ruby/rails version issue, but I am using Rails 4.2.2 and Ruby 2.3.0 on an IDE, but "rails test" (as Hartl instructs to use) won't work (kicks back "test Command not found"). Not sure if that's a hint to a bigger problem or unrelated. Thanks in advance!

EDIT: Links using these paths (like below) are rendering correctly, it is just failing the tests.

<%= link_to "Home",   root_path %>  <%= link_to "Help",   help_path %>  

Ruby On Rails Flash.each creating curly brackets on page, not going away

Posted: 01 Jul 2016 07:48 AM PDT

I am currently taking a course on Ruby on Rails and it is going well, but when i get to doing a flash.each (code below) i keep getting {} showing up on my actual page, only when i delete the line of code does it go away.. I have not a clue why

<%= flash.each do |key, value| %>     <%= content_tag :div, value, class: "alert alert-#{key}" %>  <% end %>  

That is the code that is in my Application.html.erb file they connect with this

class ContactsController < ApplicationController    def new      @contact = Contact.new    end      def create      @contact = Contact.new(contact_params)        if @contact.save        flash[:success] = "Message Sent"        redirect_to new_contact_path      else         flash[:danger] = "Message not sent ID10T ERROR occured"        redirect_to new_contact_path        end    end  end  

The success and danger are bootstrap classes btw...

On top of the rouge {} just chilling on my page i get a {"success"=>"Message Sent"} appearing below my Message Sent notice... I am stumped and while i can live with it like that, I do not want to go half on my first rails app.. All help is appreciated.. I will link the website so you can see what I am talking about, I will leave the server running as long as i can, to see the {success => message} just fill out a fake name email and comment and click submit... Thanks so much

https://udemy-rails-coder-nohashkang.c9users.io/contacts/new

syntaxt error on rake asset precompile for production

Posted: 01 Jul 2016 07:39 AM PDT

I am trying to push my app to heroku,

When I am doing $ bundle exec rake assets:precompile RAILS_ENV=production RAILS_GROUPS=assets

I am getting

rake aborted! Sass::SyntaxError: Invalid CSS after "...overflow:hidden": expected "{", was ";width:100%;hei..." (sass):6888

Not able to figure out the exact issue here. Can someone help me out.

Sass-Rails @import, do global imports have to be imported in each stylesheet or just application.scss?

Posted: 01 Jul 2016 07:30 AM PDT

In our current project app, I hope to eventually get to cleaning up our CSS/SASS assets. As I was reviewing what we have, we have tons of @imports all over our files, i.e. some global variables are contained in an seperate file and we import that file in several other stylesheets at the top. However, in our platform.scss (pretty much our application.scss), at the top I call to @import all our global variable files. Is it necessary to @import other stylesheets at the top of each stylesheet that requires it or could I just potentially only @import those global stylesheets at the top of our platform.scss so I only have to import once.

A snippet from my Gemfile.lock. rails (4.1.14.2) actionmailer (= 4.1.14.2) actionpack (= 4.1.14.2) actionview (= 4.1.14.2) activemodel (= 4.1.14.2) activerecord (= 4.1.14.2) activesupport (= 4.1.14.2) bundler (>= 1.3.0, < 2.0) railties (= 4.1.14.2) sprockets-rails (~> 2.0) sass (3.4.13) sass-rails (5.0.1) railties (>= 4.0.0, < 5.0) sass (~> 3.1) sprockets (>= 2.8, < 4.0) sprockets-rails (>= 2.0, < 4.0) tilt (~> 1.1)

Rails Sidekiq Redis long operation due to brpop

Posted: 01 Jul 2016 07:25 AM PDT

Newrelic monitoring on fresh Ruby on Rails application with Sidekiq, and not much logic yet implemented and not much trafic is showing that Redis is taking long time (around 2s-3s) on brpop operations.

why is that?

is that an issue in terms of performance?

Can I consume Navision Web Services (Odata / SOAP) using Ruby On Rails?

Posted: 01 Jul 2016 07:25 AM PDT

I am trying to consume Web Services (NAV 2016) using Ruby on Rails but stuck at a point when hitting the (SOAP) URL system returns an HTTP authentication error.

Does any one have idea or any links for same.

Any help appreciated. Thanks, kapil

Custom ActiveJob Class for ActionMailer

Posted: 01 Jul 2016 07:15 AM PDT

In my rails application I'm using ActionMailer to send emails in the background with the help of ActiveJob. The problem is that sometimes I'm receiving an ActiveJob::DeserializationError when the record has been destroyed. I know that I can use rescue_from to catch this exception but I would need to use a custom job class.

How can you instruct actionmailer to enqueue your jobs using a custom class?

Conditional content based on url

Posted: 01 Jul 2016 07:13 AM PDT

I'm looking to show content based on whether a certain tracking url was used to access the page. I have looked into request.referrer, but can't seem to get it to function.

What is the best way to show/hide content using rails for example

Hide for: www.yourcompany.com/web Show for: www.yourcompany.com/web?test

Get current status of a delayed job in Sidekiq (through Active Job?)

Posted: 01 Jul 2016 07:04 AM PDT

I use rails 4.2.5 and Sidekiq for background processing.

There is an API which an application can call.

I now have this code:

def start_item(name, init_query)    job_id = AzureBufferBase.delay.execute_in_transaction(name, init_query)    job_id  end  

I get a job_id back like this: ef95bdd9cf5da0ef1273db6c

Now I want to expose this status through the API:

module Api    class BackgroundJobsController < BaseApiController      def show        result = Sidekiq::Status(params[:id])        render json: { 'status' => result.to_json }, status: 200      end    end  end  

Sidekiq::Status: this doesn't work, but my question is, how can I get the status from Active Job of a job (queued, progress, completed, ...)?

Figuring Out How To Access Methods

Posted: 01 Jul 2016 07:38 AM PDT

I have an advertiser model and an experiment model. I've setup the associations as follows:

Advertiser has_many :experiments    Experiment belongs_to :advertisers  

The experiments table has a column titled "experiment_type", which can either be AOV or Conversion. I am trying to display experiments for the particular advertiser by experiment_type.

I can successfully display ALL of the experiments by advertiser with the following iteration

<% @advertiser.experiments.each do |experiments| %>   <td><%= experiments.id %></td>   <td><%= experiments.name %></td>  <% end %>  

Or I can successfully display all the experiment_type with the following iteration

<% @aov.each do |experiments| %>   <td><%= experiments.id %></td>   <td><%= experiments.name %></td>  <% end %>  

What I cannot figure out is how to show the experiment_type by advertiser. I thought something like

<% @advertiser.aov.each do |experiments| %> would work, but it gives me an

undefined method `aov' for #

The aov action within my experiments controller is

def set_aov_experiments      @aov = Experiment.where("experiment_type = ?", "AOV")      end  

Any help would be appreciated. Thanks in advance.

Active Record Relation for Assigned and Created

Posted: 01 Jul 2016 07:35 AM PDT

I currently have a working Active Record association but I was wondering if there was a more efficient way of doing something like this. Basically I have a model called Task. A task has one creator and can be assigned to many people. The user model is a Devise Model called User. This is my current setup but I don't like the query I need to use to fetch all Tasks for a user whether they created them or were assigned to them. Here are my models. My current setup is also terrible with pagination. Any suggestions?

class Task < ActiveRecord::Base    has_and_belongs_to_many :users    belongs_to :creator, foreign_key: 'creator_id', class_name: 'User'  end    class User < ActiveRecord::Base    has_and_belongs_to_many :assigned_tasks, class_name: 'Task'    has_many :created_tasks, foreign_key: 'creator_id', class_name: 'Task'      def tasks      (assigned_tasks.includes(project: [:client]) + created_tasks.includes(project: [:client])).uniq    end  end  

So basicslly a Task has to have:

  • One creator (User)
  • Many Users assigned to it

Save data from api (but just once)

Posted: 01 Jul 2016 07:33 AM PDT

I would like to save the data from the API, but just once. Currently it's saving data each time I reload my page, so I have the same entry lot of times... I just want to save new one if they are. When I try to add validation to avoid this I get this error :

Validation failed: Date has already been taken, Url has already been taken

This is my code :

schema :

 create_table "conferences", force: :cascade do |t|    t.string   "title",      null: false    t.string   "url"    t.date     "date",       null: false    t.datetime "created_at", null: false    t.datetime "updated_at", null: false  end  

conference.rb:

class Conference < ActiveRecord::Base  validates_presence_of :title, :date  validates :date, :url, :uniqueness => true     def self.save_conference_from_api    response = ApiMeetup.new.events('parisrb')    api_data = JSON.parse(response.body)    parisrb = []    api_data.each do |event|      if event["name"] == "ParisRb.new(premier: :mardi, pour: :talks)"        parisrb << event      end    end    parisrb.map do |line|      conference = Conference.new      conference.title = line['name']      conference.date = line['time']      conference.url = line['link']      conference.save!    end    Conference.all   end  end  

conferences_controller :

def index    @conferences = Conference.save_conference_from_api  end  

index :

%ul    - @conferences.each do |conf|      %li        %span          = conf.date  

Rails redirect sending me to localhost:3007

Posted: 01 Jul 2016 06:23 AM PDT

I'm working on a Rails application and i'm having the following problem.

I'm using a gem called Wicked. Basically what the gem does is allow the programmer to define steps in a controller and for each step in the show action of that controller render a different view.

Something like these

class MyController < ApplicationController    steps :one, :two, :three, :four      def show      requested_step = params[:id]        if some_condition        render_step requested_step      else        redirect_to action: "show", id: "four"      end    end  end  

So, you have steps one, two, three, four and you request something like "my_controller/one" that takes the :id as "one" in the controller and renders one.erb for example.

All cool for now.

BUT

When i call the redirect_to like in the code above it redirects me to localhost:3007/my_controller/four. Yes, port 3007 instead of 3000. And obviously my site can't reach that URL.

I already checked if i have another server fire up or another process that could be bother and generating this redirect going to port 3007. But it wasn't the case.

Is just this redirect that sends me to 3007. Any other request goes just fine to port 3000.

Any one with a similar problem sometime?

Thanks

My Rails version is 4.2.6

How to avoid Mongoid (or MongoDB) replacing empty arrays with null

Posted: 01 Jul 2016 06:20 AM PDT

Background: I have built an API in Rails and a client in Angular. My API will connect to a third party API and grab some data. This data will come in as an nested object/hash which is stored in MongoDB/Mongoid.

When my Angular clients manipulates the data and send it to my API to save it, all empty arrays within the nested hash/object are replaced with null.

Is there a way I could avoid this from happening (other than manually converting all the nulls back to array but that would be tedious and complex as I'd need to push this updated data to the third part API also)?

Rails Console - Group By count and display referenced column value

Posted: 01 Jul 2016 06:18 AM PDT

I have 2 models, Bug (id, status_id) and Status(id, desc)

How can I get the output like bug_status_desc, bug_count

the output should be

{NEW=>1, REOPEN=>2}  

This is what I have tried.

Bug.group(:status).count  

Result is

(0.8ms)  SELECT COUNT(*) AS count_all, status_id AS status_id FROM `bugs` GROUP BY `bugs`.`status_id`  ORDER BY created_at DESC  Status Load (0.4ms)  SELECT `statuses`.* FROM `statuses` WHERE `statuses`.`id` IN (1, 3)  =>   {#<Status:0x007fb210991370 id: 1, desc: "NEW">=>1,  #<Status:0x007fb210991118 id: 3, desc: "REOPEN">=>2}  

Make read-only column in spreadsheet using spreadsheet gem

Posted: 01 Jul 2016 06:05 AM PDT

I have used spreadsheet gem to generate xlsx, I wants to make read-only for some particular columns and rows.

How to do with spreadsheet gem?

How to fetch all associated grand children records?

Posted: 01 Jul 2016 06:40 AM PDT

How to tell ActiveRecord to fetch all links from all Canvases that belong to particular AdTemplate? I have created a canvases_links method for it, but maybe ActiveRecord has some association methods that work out of the box?

class AdTemplate < ActiveRecord::Base      has_many :canvas        def canvases_links        canvas.includes(:links).map do |canva|          canva.links        end.flatten      end      end    class Canva < ActiveRecord::Base      belongs_to :ad_template      has_many :links      has_many :close_areas  end    class Link < ActiveRecord::Base    belongs_to :canva  end      a = AdTemplate.find(1)  a.canvases_links # works okay  a.active_record_magic_method_links # must return the same data as a.canvases_links method :)  

Rails prevent column from breaking

Posted: 01 Jul 2016 08:23 AM PDT

In Rails, I have a table with four columns. I want two of the columns to essentially never break if at all possible. I want the other columns to shrink and continue breaking while these two remain the same. Currently, shrinking my window simply causes all of the columns to break at the same time and shrink the table to half its size, and it ends up much smaller than the screen. I've tried using col-sm-2, col-md-2, etc. but these aren't changing the breakpoint for me at all. Essentially my issue is that all of my columns break at the same point, which is behavior I do not want

Putting an Ember partial inside Rails view

Posted: 01 Jul 2016 05:21 AM PDT

I have an application in Rails. Recently Ember was installed, and is being used on the part of the views. It works fine there. Now, I need to add some ember functionality to the navbar. At the moment navbar is the part of the Rails layout. I've never dealt with ember before, I've only read some tutorials.

The first solution I've found so far is rewriting and moving the navbar from Rails layout to Embers layout. But that seems like a lot of work, and I'm not sure if it is a good idea.

There is also a way, of puting a div named, for example, "ember-app" and root the Ember there. But that works for a whole ember app, and I want only a part in navbar, and something else in the body. Essentially, what I would like to do, is something like this

<body>    <div class="navbar">       *rails things*        <div id="ember-navbar-part></div>        *more rails things*    </div>    <div id="ember-body-part">    </div>  </body>  

Is it possible? There are some ember partials things I've found, but they work inside embers app. Maybe moving the navbar into embers app is normal things?

rails has_one association preventing adding new child object if exists

Posted: 01 Jul 2016 05:11 AM PDT

In my rails app I have user has_one :profile and profile belongs_to :user association. If a user already has a profile and goes to the user/:user_id/profile/new page and submits a new profile, then the old profile gets updated.

I can prevent this with pundit (authorization gem) and authorize only users who don't have profile to be able to trigger new and create actions. I was wondering though what's the rails convention was in this case. I guess there should be a simpler solution.

Rails 4 Concurrency Issue - After Unlocking Record & Reloaded Attributes

Posted: 01 Jul 2016 04:57 AM PDT

I am having hard time understanding the reason why my model is behaving like this. It's taking an unexpected behavior that I would like to understand the reason.

I have 2 actions, cancel and feature, when attribute was already canceled it can't be featured. To ensure that a feature is not performed on a canceled attribute I am using RedisMutex to lock and make the proper verifications inside the block, when the lock is made and is exclusive:

mutex = RedisMutex.new(record_to_feature, block: 30, sleep: 0.1)  if mutex.lock      record_to_feature = record_to_feature.reload        if record_to_feature.reload.active?          record_to_feature.reload.update_attributes(featured: true)      end      mutex.unlock  end  

I have the similar logic on the cancel action - locking with redis-mutex and making the verifications inside the lock.

I want to understand how is it possible that sometimes (rare) the attribute is first canceled and then featured - the other way feature and then canceled may also occur just I haven't detecte dit

devise edit form with bootstrap

Posted: 01 Jul 2016 07:36 AM PDT

In my edit view, I want to apply bootstrap. However, when replacing...

<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>      <%= devise_error_messages! %>      <div class="row">        <div class="col-md-6">          <div class="row form-group">            <div class="col-md-4"><%= f.label :username %></div>            <div class="col-md-8"><%= f.text_field :username %></div>          </div>  

with this...

<div class="row">    <div class="col-md-4">       <div class="form-group">          <label class="sr-only" for="username">Username</label>          <input type="text" class="form-control" name="username" placeholder="Username" value="<%= f.text_field :username %>">         </div>    </div>  </div>  

I get this as output enter image description here

I have tried many alternatives to include erb but don't understand the issue. How should I include the field in my edit forms?

AWS OpsWorks use file as an Environment Variable

Posted: 01 Jul 2016 05:26 AM PDT

Cheers! Is there any possibility to use File (.pem certificate in my occasion) as an AWS OpsWorks Environment Variable? As far as I could see, AWS OpsWorks allows to set only direct string values through it's console on app's level.

Or maybe there are some best practices of storing .pem certificates on AWS that depends on environment?

nested forms with pre populated data

Posted: 01 Jul 2016 03:49 AM PDT

I am having an issue managing a has_many :through association via nested form

when creating a product i want to display all tags from tags table and create a new record in product_tags table with some extra information

is this possible thanks for help

Models

class Product < ApplicationRecord    has_many :product_tags    has_many :tags, through: :product_tags      accepts_nested_attributes_for :product_tags, :reject_if => :all_blank, :allow_destroy => true  end    class ProductTag < ApplicationRecord    belongs_to :product    belongs_to :tag  end    class Tag < ApplicationRecord    has_many :product_tags    has_many :products, through: :product_tags  end    View  = simple_form_for @product do |f|    = f.input :name    = f.input :price    = f.fields_for :tags do |tag|      b tag.object.name      = tag.fields_for :product_tags do |product_tag|        = product_tag.input :tag_id, as: :hidden, input_html{value:tag.object.id}        = product_tag.input :priority        = product_tag.input :status  

No comments:

Post a Comment