ruby-on-rails,forms,nested , Rails nested forms -> different treatment depending on value

Rails nested forms -> different treatment depending on value


Tag: ruby-on-rails,forms,nested

I have this tricky question regarding nested forms. Just say I have the following models:

  1. restaurant
  2. employees, in which employees belongs_to restaurant.

I also have two types of employees within the employees model,

  1. managers
  2. staff

The managers are designated via manager attribute in the employees model, it is a boolean.

When I go edit the list of employees for each restaurant, it is through a nested form,i.e:

<%= f.simple_fields for :employees do |f| %>
  <%= render 'employee_fields', :f => f %>
<% end %>

MY QUESTION: Is there any way to render different partial forms depending on the type of employee? For example, if the current employee is a manager, then

<%= render 'manager_fields', :f => f %>. 

Otherwise, if the current employee is a staff, then

<%= render 'staff_fields', :f => f %>.


Yes, using ternary operator :

<%= render f.object.manager? ? 'manager_fields' : 'staff_fields' , :f => f %>

If you can change your design, I have a better solution for you. Which follows as :

Use Rails enum feature.

Add a field desgination as an integer field in your Employee model using migration.

Then inside the model:

enum designation: [ :staff, :manager ]

Then you will be storing say in a column designation, either manager ( value is 1) or staff(value is 0). Now inside the view call <%= render f.object.desgination , :f => f %> . And you should have _manager.html.erb and _staff.html.erb 2 partials.

And you are done!


Rails - Simple Form - Nested Resources paths

I am trying to make an app in Rails 4 using simple form. I have 3 models: Project, Project_Question, Project_Answer The associations are: Project: has_many :project_questions, dependent: :destroy#, through: :projects accepts_nested_attributes_for :project_questions Project Question: belongs_to :project#, counter_cache: true has_one :project_answer, dependent: :destroy belongs_to :user accepts_nested_attributes_for :project_answer Project Answer: belongs_to :project_question#,...

paper clip show image url is undefine

I want to show image in each loop and image is upload by paperclip gem. The real path is /system/users/images/000/000/035/original/lovecupcake.jpg When i use this this is working fine rails code <%= image_tag @user.image.url(:medium) %> output <img alt="Lovecupcake" src="/system/users/images/000/000/035/original/lovecupcake.jpg"> it show me image but when i apply loop <% @result.each do...

Javascript not executing when using link_to

I have couple javascript functions that attaching action to buttons in controller view some/index. I navigate to some/index using link_to method. But when i'm using link_to method, buttons has no attached javascript actions (in some/index view). When i try open some/index directly from my browser, buttons have all attached actions...

Allowing some enabled and disabled option on collection_select

I am trying to populate a dropdown box on a view that has all the states. This works just fine: <%= f.collection_select :state_id, @states, :id, :name %> Now, I need to make the following: Some states are going to be disabled for choosing, but they still have to appear on...

Same enum values for multiple columns

I need to do something like this: class PlanetEdge < ActiveRecord::Base enum :first_planet [ :earth, :mars, :jupiter] enum :second_planet [ :earth, :mars, :jupiter] end Where my table is a table of edges but each vertex is an integer. However, it seems the abvove is not possible in rails. What might... not getting saved in form

I have 2 models, promos and users. Promo belongs_to :user User has_many :promos In my routing, I have nested resources: devise_for :users resources :users do resources :promos end I have a form to create new promos, with simpleform <%= simple_form_for [current_user, @promo] do |f| %> <%= f.input :title, label: "Título...

Active Record Where Clause For Relation In Model

I have two Models User and Site. The User has category like 'basic and premium'. The user has relation to sites one -> many (i.e one user can have more than one sites). Now i want to select sites of premium user. Can someone tell me how to use where...

On rendering from controller, current_page method does not seem to work

I have a navigation bar included in application.html.erb. Because for some pages, such as the signup page, I need to place additional code inside the navigation bar, I have excluded those pages for showing the navigation bar through application.html.erb and instead included it in their respective view pages. See code...

Can't map a range of dates in Ruby/Rails

I'm trying to map a range of dates and pass them to my view as an array, as follows: from, to = Date.parse("2014-01-01"), Date.yesterday date_range = ( @mapped_dates = {|date| date.strftime("%b %e")} I reference them in some JS in my view as follows: dateLabels = <%= raw @mapped_dates.to_json %>;...

How to find a record from database by using find_by with two fields?

I want to find a record from database in ruby on rails by using find_by with two fields. How can I accomplish it?

Ruby: How to copy the multidimensional array in new array?

seating_arrangement [ [:first, :second, :none], [:first, :none, :second], [:second, :second, :first], ] I need to copy this array into new array. I tried to do it by following code: class Simulator @@current_state def initialize(seating_arrangement) @@current_state = seating_arrangement.dup end But whenever I am making any changes to seating_arrangement current_state changes automatically....

Make instance variable accessible through hash in Ruby

In Rails, ActiveRecord objects, attributes are accessible via method as well as through Hash. Example: user = User.first # Assuming User to be inheriting from ActiveRecord::Base # Accessing attribute 'name' via method user[:name] # Attribute 'name' is accessible via hash as well How to make instance variables accessible through...

Mongoid HABTM relationships across embedded documents

I'm trying to create a Mongoid N-N reference association between two embedded documents in Rails 4 however I'm finding it difficult to get my head round how this is done. I started by adding the HABTM association to the relevant models below (Track and Option) but of course I'm getting...

Rails less url path change

Developing a Rails application with the less-rails gem I found something unusual : // app/assets/common/css/desktop/typo.less @font-face{ font-family:'SomeFont'; src:url("fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); // ... } The requested font is app/assets/common/css/fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot This font is compiled with less and the results is : @font-face { font-family: 'SomeFont'; src: url("desktop/fonts/db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); //... } Do you know why is...

Redirect if ActiveRecord::RecordNotUnique error exists

I have the next code to save: Transaction.create(:status => params[:st], :transaction_id => params[:tx], :purchased_at =>! But how can I redirect to main root page if this ActiveRecord::RecordNotUnique error appears? Can I catch this error?...

If statement for search field in Rails

I have a blog site and recently added a search bar for visitors to browse through blog posts. When used, all of the posts go away in the directory and only those which return via the search appear. In order to show the general directory and view all, I would...

Can Rails deal with DB uniqueness without index?

I see add_index ~ unique: true statement in schema.rband think uniqueness is constraint for table, not for index.Using index is one of way realizing uniqueness, Programmer should not designate to the RDBMS "how" and index quicken searching but take costs inserting. In fact, is there another way to keep uniqueness...

Rails basic auth not working properly

I am building a small API that uses basic authentication. What I have done, is that a user can generate a username and password, that could be used to authenticate to the API. However I have discovered that it is not working 100% as intended. It appears that a request...

Rails shared controller actions

I am having trouble building a controller concern. I would like the concern to extend the classes available actions. Given I have the controller 'SamplesController' class SamplesController < ApplicationController include Searchable perform_search_on(Sample, handle: [ClothingType, Company, Collection, Color]) end I include the module 'Searchable' module Searchable extend ActiveSupport::Concern module ClassMethods def...

How to pass array in rails 4 strong parameters

I have to pass a array of food_item_ids in my order_controller. Every order will have many food_items. How can I pass these food_items_id as an array in strong parameters. orders_controller.rb def create @order = if render :json, @order, status:201, location: [:api, @order] else render :json, { errors: @order.errors...

How to send a mail by postfix mail server with rails?

On my local host, I followed this article made a mail server and it works well. I want to develop a mailer feature with rails framework. Here are my settings: # mailer config.action_mailer.default_url_options = { :host => '' } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'localhost', port: 25,...

rendering the partials in controller after the validation check

I have two partial views for two different sign up forms. On my home page , based on the link one clicks on, I'm rendering respective form.(views/application/index) = link_to 'Mentor', new_user_path(user_role: true), :class =>'btn' = link_to 'Mentee', new_user_path, :class =>'btn' In views/users/new.html.haml , I'm checking the user role and redirecting...

RoR Tutorial Chapter 3 - Guard detects changes but doesn't fully execute tests

I'm currently following the book and the video and in the video, Hartl runs a guardfile so that it automatically runs tests after any changes have been made. So in the videos when he presses return whilst in guard mode, it says: 17:35:31 - INFO - Running: test/controllers/static_pages_controller_test.rb followed by...

Getting a collection via Ajax to show in view

All I'm trying to do is have a collection populate in the view when a user clicks a button. But I feel like I'm making this way too complicated and it's not working. See my code - where am I going wrong? Click handler: $('#filterrific_results').find('.followup-injury').on('click', function(e){ e.preventDefault(); $.ajax({ url: "/assessments/followups",...

Angular submit not called when required fields not filled

I'm creating a form in Angular with Ionic. I don't want a red error class to be displayed unless a user has submitted the form. As such, my code looks like this: <form ng-submit="submit()" name="form"> <ion-radio ng-repeat="item in items" ng-model="data.type" name="type" ng-value="item.value" ng-class="{'error' : form.type.$invalid && formSubmitted }" </form> And...

Rails: get f.range_field to submit null or nil as default value

In my app, I have a range_field where a user can select 0..100. But if they don't select anything, I want the form to submit "null" or nil as the value rather than a numerical value. Is this possible? If I use the below syntax, then everything works except value...

What is Rack::Utils.multipart_part_limit within Rails and what function does it perform?

Rack::Utils.multipart_part_limit is set to 128 by default. What purpose does the value have and what effect does it have within the Rails system?...

In Ruby how to put multiple lines in one guard clause?

I have the following line of code : if params[:"available_#{}"] == 'true' @deliverycharge = @product.deliverycharges.create!(districtrate_id: delivery_custom_price(district) end Rubocop highlight it and asks me to use a guard clause for it. How can I do it? EDIT : Rubocop highlighted the first line and gave this message Use a guard...

Heroku RAM not increasing with upgraded dynos

I have a massive function i have been calling manually through the heroku rails console. I have been receiving the error rapid fire in my logs: 2015-06-22T14:56:42.940517+00:00 heroku[run.9877]: Process running mem=575M(112.4%) 2015-06-22T14:56:42.940517+00:00 heroku[run.9877]: Error R14 (Memory quota exceeded) A 1X dyno is suppose to have 512 MB of RAM. I...

Stack level too deep because recursion

I have a model named Tweet. The columns of the Tweet model are: -id -content -user_id -picture -group -original_tweet_id Every tweet can have one or multiple retweets. The relation happens with the help of original_tweet_id. All the tweets have original_tweet_id nil , whilst the retweets contain the id of the...

Active Record association links, but can't assign values

I'm setting up permissions for each user to determine what access they have to certain data. I have a user model and a permission model that is set up with a has_many and belongs_to association like so: app/models/permission.rb class Permission < ActiveRecord::Base has_many :users end app/models/user.rb class User < ActiveRecord::Base...

Routes work in Development But not in Production

Weird Error. I have some routes that work perfectly during development but once i deploy and try to access them it comes up with page does not Exist error I have the following routes.rb file: TransportUnl::Application.routes.draw do resources :trucks resources :shipments do collection do get :autocomplete_location_cs end end devise_for :users...

Sorting in Ruby on rails

I'm very new to Ruby on rails. I try to edit the following api. I want to sorting "can_go" which is true are shown at the top of list. I added this row before sending data, but the result is still order by "user_id". user_infos.sort { |a, b| - (a['can_go']<=>b['can_go'])...

Is it possible to have two callbacks in around_destroy in rails?

Although this can be accomplished as follows: class Model < ActiveRecord::Base around_destroy :callback def callback puts 'callback1 before yield' puts 'callback2 before yield' yield puts 'callback1 after yield' puts 'callback2 after yield' end end But I wish to do the following: class Model < ActiveRecord::Base around_destroy :callback1, :callback2 def callback1...

Ruby on Rails - Help Adding Badges to Application

I'm creating a rails application that is a backend for a mobile application. The backend is implemented with a RESTful web API. Currently I am trying to add gamification to the platform through the use of badges that can be earned by the user. Right now the badges are tied...

Broken Rails integration after moving 'micropost feed' - Expected at least 1 element matching “div#error_explanation”, found 0

After following Michael Hartl's Rails Tutorial I moved the 'micropost feed' from / to /members, and now when I submit a post that doesn't validate properly (too many characters, missing content etc.) rails returns an error saying: ArgumentError in MicropostsController#create First argument in form cannot contain nil or be empty...

Show only the requested forms using JS

As the image below illustrates, I have two forms and two buttons. Currently all the forms are visible. How can I only show the requested form "according to the option they have selected (from the blue buttons on the top)"? So, if the user clicked on the "send an invite"...

Rails Generates Blank Record Even Input Data

I am learning to use CRUD, and setup a page to add a record, however it only generated blank record? Can you take a look my code? thanks! here is the Page controller: class PagesController < ApplicationController def index @test = Page.all end def new @test = end def...

Rails: Posting from a form to a M:M table

On the group index page I display a listing of group discussions and a form to create a new discussion. class Group < ActiveRecord::Base has_many :discussions end class Discussion < ActiveRecord::Base belongs_to :user belongs_to :group end Controller: class DiscussionsController < ApplicationController def index @group = Group.find(params[:group_id]) @discussion ={group_id:})...

Showing and editing has_many objects in Rails

I'm trying to do something that I imagine to be very basic, but I'm very new to Rails and am not sure what sure what I'm doing wrong. I've gone through several tutorials and searched for an answer and can't find what the issue is. Would appreciate any help! I've...

Seeding fails validation for nested tables (validates_presence_of)

An Organization model has a 1:many association with a User model. I have the following validation in my User model file: belongs_to :organization validates_presence_of :organization_id, :unless => 'usertype==1' If usertype is 1, it means the user will have no organization associated to it. For a different usertype the presence of...

ActiveAdmin ::Show 4 textbox in active admin using has_many relationship

I have one poll table having with question filed and each question have 4 answer which is has_many relation ship with answer table class Poll < ActiveRecord::Base has_many :answer end My answer model class Answer < ActiveRecord::Base belongs_to :poll, :class_name => "Poll", :foreign_key => "question_id" end My active admin form...

Entering data into mysql database using php

Customer will complete a form and enter a pathway where they will want the CSV to be exported to. The pathway is entered using the top section of the php (below): <form action="register.php" method="post"> Enter file pathway where CSV will be saved: <input type="text" name="username" required="required"/> <br/> <input type="submit" value="Enter"/>...

Heroku rake db:migrate failing - uninitialized constant

My app is working fine locally and my push to Heroku was successful. But, when I run heroku run rake db:migrate, I get the following error: NameError: uninitialized constant AddWeightToExercises Here is the failed migration: class AddWeightToExercise < ActiveRecord::Migration def change add_column :exercises, :weight, :float end end edit: Thanks for...

Rails Association Guidance [on hold]

I am new to rails 4. I have gone through lots of tutorials and trying to solve below scenario. But still no success. Can anybody point me in the right direction. How to handle associations for below scenario. Scenario: 1. Patient can have many surgeries. 2. Surgery has two types...

Symfony 2 unable to pass entity repository to form

I have a form with a drop down and a set of checkboxes, i've used entity form field type to get the values via DB. it works with one of the entity but not with the other. i have this code seperately inside AddBadgesType there is NO AddBadges entity <?php...

Rspec view test with url parameters

I have a page dashboard.html.erb that may be redirected to from several different controllers/actions. When it receives the redirect, it also receives several url parameters. Controller code: class PlansController def some_action redirect_to dashboard_path(show: "default", cool_array: ["test", "test"]) end end class StaticpagesController def dashboard end end View code: <% if cool_array...

Rails - link_to path based on object's name + refactoring multiple custom actions

I'm looking to simplify the link_to path based on thr object's name and also am looking into refactoring multiple custom actions. I've managed to get this working below. <% ServiceMenu.all.each do |menu| %> <tr class=" <%= cycle('odd', 'even') %>"> <td><%= link_to, ("tech/""#{}") %></td> </tr> <% end %> I feel...

Run AJAX function on form submit button after javascript confirm() cancel

I have a form where and AJAX function runs on form submission to make sure that the data in the form doesn't conflict with data in the database. If a conflict is found, the AJAX function pops up a confirm() box. If the user clicks "OK", the form is submitted....