Menu
  • HOME
  • TAGS

rails simple_form using virtual attributes

Tag: ruby-on-rails-4,autocomplete,simple-form,model-associations,virtual-attribute

I am trying to incorporate Simple_forms into my app using a virtual attributes. I am following http://railscasts.com/episodes/102-auto-complete-association-revised to get autocomplete to work as well. Simple_form works when i do not use a virtual attribute but when I do use the virtual attribute I get the error "Association :head_coach_name not found".

My Team Model is:

class Team < ActiveRecord::Base
  attr_accessor :head_coach_name
  belongs_to :user
  validates :team_name, presence:   true
  belongs_to :head_coach, class_name: "User", :foreign_key => "head_coach_id"

  def head_coach_name
    user.try(:name)
  end

  def head_coach_name=(name)
    self.user = User.find_by_name(name) if name.present?
  end
end

My User model is:

class User < ActiveRecord::Base
  has_many :teams, :class_name => "::Team", dependent: :destroy
end

My View:

                <%= simple_form_for @team, html: {class: 'form-horizontal' }, url: teams_path, method: 'post' do |f| %>     
                <%= f.error_notification %>         
                <%= f.hidden_field :user_id %>                  
                <div class="col-md-6">
                    <div class="row">
                        <div class="col-md-12">                         
                                <%= f.input :team_name, class: "form-control" %>        
                                <%= f.input :year, collection: Date.today.year-90..Date.today.year  %>  
                                <%= f.input :season, as: :select, collection: 
                                    ['Fall',
                                    'Winter',
                                    'Spring',
                                    'Summer'] %>                        
                                <%= f.input :season_type, as: :select, collection:
                                    ['Outdoor',
                                    'Indoor',
                                    'Tournament'] %>
                                <%= f.input :awards %>  
                        </div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="row">
                        <div class="col-md-12">         
                                <%= f.input :club %>        
                                <%= f.input :division %>
                                <%= f.association :head_coach_name %>                       
                                <%= f.input :assistant_coach_id %>          
                                <%= f.input :assistant_coach_two_id %>
                            </div>                                              
                        </div>
                    </div>          
                <%= f.button :submit, label: "Add team", class: "btn btn-large btn-primary col-md-3 pull-right" %>
                <% end %>   

Everything works as long as i don't have the virtual association in there. I could put :head_coach and it would work with a drop down list but I want to use the autocomplete feature like in the railscast video. Also in rails console i can run these commands to show the virtual attribute works:

2.1.2 :003 > team.head_coach_name
  User Load (0.6ms)  SELECT  `users`.* FROM `users`  WHERE `users`.`id` = 100 LIMIT 1
 => "Miss Daisha Shanahan"

Any ideas on how I can get the virtual attribute to work correctly with simple_forms?

Best How To :

You are referencing an association that doesn't exist with f.association :head_coach_name. Try this instead:

f.association :head_coach, label_method: :head_coach_name

You have a few other oddities in your code, including your head_coach_name definition, which should rely on head_coach instead of user. Same concern for the head_coach_name= method.

Example. You have:

def head_coach_name
  user.try(:name)
end

Seems like you should have:

def head_coach_name
  head_coach.try(:name)
end

Error when trying to install app with mysql2 gem

mysql,ruby-on-rails,ruby,ruby-on-rails-4

The error log says: ld: library not found for -lssl So, you need to install libssl: brew install openssl Hope it helps....

autocomplete rails routes issues

jquery,ruby-on-rails,autocomplete

You need a member route for this to work (since you are trying to access "/rfqs/1/autocomplete_customer_name"): get :autocomplete_customer_name, :on => :member Member routes add an :id param in the route, while the collection routes work without id params: resources :items do get :foo, on: :member get :bar, on: :collection end...

Rails add hash into existing hash

ruby,ruby-on-rails-4

The solution is convert to hash result after select from db using @user.as_json a = Hash.new a[:profile] = @user.as_json a[:profile][:contacts] = @user.contacts.all ...

How to exclude guest users from getting emailed Rails 4 Devise

ruby-on-rails,email,ruby-on-rails-4,devise,mailer

def welcome_email(user) # The following line is unnecessary. Normally, you do # something like this when you want to make a variable # available to a view #@user = user # You can make the if more explicit by writing # if user.id == nil, but if will return false...

Using the Rails console to delete odd-numbered records

ruby-on-rails-4,command-line,console

You can use Hero.where('id MOD(2)!=0').destroy_all ...

Migrate from existing password_digest column?

ruby-on-rails,ruby-on-rails-4,devise,bcrypt

Simply write a migration to rename the column name, it will not loose your data. rails g migration ChangeColumnName this will generate a migration file class ChangeColumnName < ActiveRecord::Migration def change rename_column :users, :password_digest, :encrypted_password end end ...

Invalid form submission clears session in Rails 4

ruby-on-rails-4,session-cookies,form-submit,session-state

Yes it looks like you dropped the '@' in a couple of places in your Create action: if current_customer @order.customer = current_customer end Should be: if @current_customer @order.customer = @current_customer end ...

ApplicationController helper method undefined in Rails

ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4

It seems that the problem is that skip_after_action does not accept a conditional argument such as if: or unless:. Even if you pass a conditional, the skip_after_action callback always executes. Unfortunately for me, this means that it is not possible to do what I wanted to do with the code....

Stack level too deep because recursion

ruby-on-rails,ruby,ruby-on-rails-4,twitter

If you express the relation properly, ActiveRecord will do it for you class Tweet belongs_to :original_tweet, class_name: Tweet has_many :retweets, class_name: Tweet, dependent: :destroy, inverse_of :original_tweet end Tweet.last.destroy # will now destroy dependents ...

How to use Rails #update_attribute with array field?

ruby-on-rails,ruby,postgresql,ruby-on-rails-4,activerecord

I don't think update_attribute is going to be useful as it will replace the array with the new value rather than append to it (but see better explanation below in --Update-- section). I'm not sure what best practices are here, but this should work to just add something if it...

autocomplete jquery element.autocomplete is not a function

jquery,angularjs,autocomplete

Please check this, http://jsfiddle.net/swfjT/2884/ the problem is need to be invoke the controller <div ng-app='MyModule'> <div ng-controller='DefaultCtrl'> <input type="text" ng-model="foo" auto-complete/> Foo = {{foo}} </div> </div> angular.module('MyModule', []).controller('DefaultCtrl',['$scope', function($scope) {}]) ...

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

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller

You can use content_for and yields to create a default in your layout which views can override. # layouts/application.html.erb: <% if content_for?(:banner) %> <%= yield(:banner) %> <% else %> <div id="banner"> <h1>This is the default...</h1> </div> <% end %> /users/signup.html.erb: <%- content_for :banner, flush: true do -%> <!-- move along,...

How to simulate the float value that appears when you type on the input

html,css,autocomplete,ionic

Guess, you need this, <input type="search" placeholder="Buscar" ng-model="search.name"> <a class="item item-avatar" ng-repeat="lugar in organizations_all | filter:search.name"> Notice, I've changed the "filter:search" to "filter:search.name". This is to bind the input value, i.e., the model in the search box, (search.name) to the list of all the names in organizations_all. hope this helps....

Javascript Changing Random Background Image Issue

javascript,html,ruby-on-rails,ruby-on-rails-4,background-image

I don't really want to get deep into your code, in two words: whatever is happening is happening because you have to wait for some actions to complete before they complete (such as animations) and you never want have timeouts within intervals. This has to be helpful: var images =...

Mongoid HABTM relationships across embedded documents

ruby-on-rails,ruby-on-rails-4,mongoid,embedded-documents

The reason you are getting the error is because of the logic below. If you are going to need to represent many-to-many relations, do not use a document model to store your state. Use a relational one === You can't represent a many to many relation without an association/reference table/object....

Make instance variable accessible through hash in Ruby

ruby-on-rails,ruby,ruby-on-rails-4,activerecord

It's not "through Hash", it's "array access" operator. To implement it, you need to define methods: def [](*keys) # Define here end def []=(*keys, value) # Define here end Of course, if you won't be using multiple keys to access an element, you're fine with using just key instead of...

Redirect Loop on Heroku with Rails 4 App, but not on local machine

ruby-on-rails,ruby-on-rails-4,heroku,dns

I discovered the answer. I am on Cloudflare's network. Turns out that if on their "Crypto" panel, if the SSL is set to "flexible" then you will get the redirect loop error. Had to set it to "Full".

Rails 4 - Javascript - trouble with .not()

javascript,jquery,html,ruby-on-rails,ruby-on-rails-4

jquery's not function will return a jquery object, not an integer. I can't validate if the rest of your logic is working but if you want to get the number of DOM elements that matches your jquery element, you should do it using the length value: if ($('PP').not('.closed').length>=2) { window.alert('already...

How do I setup a multi-option voting system using acts-as-votable?

ruby-on-rails,ruby-on-rails-4

Seem to be pretty straightforward: https://github.com/ryanto/acts_as_votable#examples-with-scopes @item.vote_by voter: @user1, vote_scope: 'blue' @item.vote_by voter: @user2, vote_scope: 'red' @item.votes_for.size # => 2 @item.find_votes_for(vote_scope: 'blue').size # => 1 @item.find_votes_for(vote_scope: 'red').size # => 1 So you'll need a set of 5 radio buttons (for 5 colors) on your page for the user to select...

adding background image in style rails 4

ruby-on-rails,twitter-bootstrap,ruby-on-rails-4,asset-pipeline

You should change "background-image:"url(image-url('lines3.png')"; into "background-image:"image-url(image-url('lines3.png')"; http://guides.rubyonrails.org/asset_pipeline.html#css-and-sass Or you can try with: background-image: url(<%= asset_path 'lines3.png' %>)...

How to iterate data from database to become a radio button in template?

ruby-on-rails,ruby,ruby-on-rails-4

You can iterate all the Status records (*). In your controller, you can add: @statuses = Status.all And in your view: <%= form_for @api, :url => commons_path do |f| %> <div class="form-group"> <%= f.label :status, "Status", class: "col-sm-2 control-label" %> <div class="col-sm-8"> <% @statuses.each do |status| %> <%= f.radio_button :status,...

Devise emails are not being sent using sendgrid while other emails are being sent well

ruby-on-rails-4,heroku,devise,sendgrid

If you switch config.raise_delivery_errors to true then you'll be able to see if there's a specific problem and work backwards from there.

Styling navbar: interaction between different styling settings

html,css,ruby-on-rails,ruby-on-rails-4

Add override class in the link_to: <%= link_to "Edit profile", edit_user_path(current_user), class:"my-dropdown-item" %> Add to CSS .my-dropdown-item { a { width: 100%; color: #000 !important; } } This might need some tweaking, let me know....

rendering the partials in controller after the validation check

ruby-on-rails,ruby-on-rails-4,model-view-controller

Why this is not working? if params[:user][:user_role] render :partial => 'users/mentor' else render :partial => 'users/mentee' end params[:user][:user_role] is nil. You can check it using lots of way: Above your if condition raise params[:user].inspect Why its nil? Reason of this is You are passing new_user_path(user_role: true) user_role true, but user_role...

Rails, default.js is empty, and jquery and jquery_ujs not loaded

jquery,ruby-on-rails,ruby,ruby-on-rails-4,rubygems

Everything is OK from your side. You said that you're on Windows 7, I also experienced this problem once when I needed to run rails on windows for some reason. Than I found an answer here which helped me to get out of this problem. Actually coffee-script-source, v 1.9.x gives...

rails - NameError (undefined local variable or method while using has_many :through

ruby-on-rails,ruby,ruby-on-rails-4

In your associations instead of fac_allocs you need to use a symbol because rails is looking a variable or method named fac_allocs instead of your associated model has_many :facs, through: :fac_allocs ...

implement has_many through association in rails 4

ruby-on-rails-4,activerecord,has-many-through

Please try this code def inventory_status @employee_inventories = EmployeeInventory.new(employee_inventories_params) if @employee_inventories.save redirect_to inventories_path else render :action => :show end end and in your view <%= link_to 'Request for inventory', inventory_status_inventory_path(@inventory, employee_inventory => {:employee_id => 1, :status => 'test'}), :class => 'btn btn-success' %> hope this will help you....

Rails 4 wicked_pdf generate blank pdf while generating from model

ruby-on-rails-4,wicked-pdf

A good test is just put a simple line of text in your template and see if you get a PDF with that line. Strip everything back so you just generating a PDF with no coming locals, just that 1 string and let me know. Here is how I set...

Rails - How to find tilt version?

ruby-on-rails-3,ruby-on-rails-4,sprockets,tilt

Use bundle show to get the versions of your installed gems. For a particular gem, like tilt, you can use bundle show tilt.

Multiple many-to-many association between two models

ruby-on-rails-4,activerecord,associations

I guess your association set up should be something like this #user.rb Class User has_many :company_admins has_many :companies, :through => company_admins has_many :followers has_many :followed_companies, :through => followers, :source => :company end #company.rb Class Company has_many :company_admins has_many :users, :through => company_admins has_many :followers has_many :followed_users, :through => followers, :source...

Rails Association Guidance [on hold]

ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2

So, the complex part of your situation is that you have one thing (Surgery) that can be of many different types, and the different types have different fields. There are a number of different approaches to this problem, and I don't believe there's wide consensus on the 'best way'. The...

How to validate in database for uniqueness?

ruby-on-rails,validation,ruby-on-rails-4

You need to put this validation into you Api model: validates :name, uniqueness: { scope: :status, message: 'your custom message' } http://guides.rubyonrails.org/active_record_validations.html#uniqueness...

How to limit access in Amazon S3 files to specific people?

ruby-on-rails-4,amazon-s3

It is not recommended to use AWS Identity and Access Management (IAM) for storing application users. Application users should be maintained in a separate database (or LDAP, Active directory, etc). Therefore, creating "one bucket per group" is not feasible, since it is not possible to assign your applications users to...

How to implement the “auto pairing of quotes” feature in custom mode in ace-editor

autocomplete,quotes,ace-editor

You could use cstyle behavior similar to the way javascript mode does see https://github.com/ajaxorg/ace/blob/v1.1.9/lib/ace/mode/javascript.js#L47 https://github.com/ajaxorg/ace/blob/v1.1.9/lib/ace/mode/behaviour/cstyle.js

Get X days out of an Array

ruby,ruby-on-rails-4

I would do: def get_days(wkn, *desired_days) get_week = Model.week(2) get_days_of_week = get_week.select { |x| desired_days.include? x.strftime("%A") } end ...

Order of including Helpers in ViewControllers

ruby,ruby-on-rails-4,method-overriding

Any controller can have a corresponding helper. For example if you have a controller named Question (questions_controller.rb), it can have a helper named questions_helper.rb. The question helper is accesible only to the views corresponding to the question controller. Besides you will have an Application helper (application_helper.rb) which is accessible to...

Rails routing link to specific show

ruby-on-rails-4,routing

rails generate migration AddPermalinkToPages permalink:string After you added then you need to create the permalink on the fly when you are saving the page or updating it. I usually do it in the model so I keep the controller clean. You can define it in a PagesHelper if you want...

Showing and editing has_many objects in Rails

ruby-on-rails,ruby-on-rails-4

Since you need to support both (POST /milestones and POST /projects/:project_id/milestones) the project_id to the form: <%= form_for [@project,Milestone.new] do |f| %> ... <%= f.hidden_field(:project_id, value: @project_id) %> ... <%- end -%> Or if your resource is always nested than project_id available in the params in your controller so you...

Controller method: Contact form should render different page depending on where the form is used

ruby-on-rails,ruby,forms,ruby-on-rails-4,controller

You can use something called action_name in Rails 4. action_name gives you the name of the action your view got fired from. Now you can send this property to the method create through a hidden field like following: <%= hidden_field_tag "action_name", action_name %> This line of code will send params[:action_name]...

Seeding fails validation for nested tables (validates_presence_of)

ruby-on-rails,ruby,validation,ruby-on-rails-4,associations

Found this : Validating nested association in Rails (last chapter) class User belongs_to :organization, inverse_of: :users validates_presence_of :organization_id, :unless => 'usertype==1' end class Organization has_many :users accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true end The documentation is not quite clear about it but I think it's worth a try....

Where is the defination of rails validators?

oop,ruby-on-rails-4

These are Rails methods: You can find valid? here and its code on Github. Likewise with new_record?, you can find a description and its source code here. Also, here is a link to the Rails repository on Github. These methods are not defined in the project, they are defined in...

How to filter values in Multiple selection using textbox value

javascript,jquery,html5,drop-down-menu,autocomplete

The .filter(function) jQuery method can be used to find the target option elements and show them as follows. The JavaScript method .toLowerCase() is used to make the search case-insensitive: $('#filterMultipleSelection').on('input', function() { var val = this.value.toLowerCase(); $('#uniqueCarNames > option').hide() .filter(function() { return this.value.toLowerCase().indexOf( val ) > -1; }) .show(); });...

How to send nested data in response , rails4?

ruby-on-rails,ruby-on-rails-4

This is something that you need to handle in the views with a proper response builder. While acts_as_api suggested by @rob works, Rails starting from v4.0 has built in support for building and sending rich JSON responses using a typical builder style DSL. It is called jbuilder - https://github.com/rails/jbuilder Just...

Rails shared controller actions

ruby-on-rails,ruby,ruby-on-rails-4

You should pass actions to the included block and perform_search_on to the class_methods block. module Searchable extend ActiveSupport::Concern class_methods do def perform_search_on(klass, associations = {}) ............. end end included do def filter respond_to do |format| format.json { render 'api/search/filters.json' } end end end end When your Searchable module include a...

Jquery .click() not working with livesearch [duplicate]

jquery,autocomplete,livesearch

Try this : You can use .on() to bind click event and use $(this) to get clicked element jQuery instance to read its data value. $(document).on("click",".result_name",function(){ //use $(this) to get clicked element and read its value $("#search_client").val($(this).data("value")); }); ...

Facing issue in edit-update action in nested form in rails4?

ruby-on-rails,ruby-on-rails-4,nested-forms

The problem is in your question_params. You have to add :id for edit/update to work correctly else it will create new records on every successful submit. def question_params params.require(:question).permit(:id, :content, choices_attributes: [:id, :option, :is_correct, :question_id]) end ...

adding link_to with image_tag and image path both

html,ruby-on-rails,image,ruby-on-rails-4,svg

Remove the space after image_tag. <%= link_to '#' do %> My Project <%= image_tag('logo.svg', "data-svg-fallback" => image_path('logo.svg'), :align=> "left" ,:style => "padding-right: 5px;") %> <% end %> ...

Ruby if else statement one line not working

ruby-on-rails,ruby,ruby-on-rails-4

You do not need to use "if" in the ternary. Change your statement to look like this: <%= current_page?(root_path) ? 'active' : 'inactive' %> ...

Redirect to edit page automatically if record exists

ruby-on-rails,ruby-on-rails-4,redirect

A redirect is a fresh request to Rails. You need to set @sale again in the edit action as it is not persisted from update. Alternatively, you can render the edit view directly from update if the update fails. That will preserve the instance variables from update....

Sortable in Rails 4

ruby-on-rails,jquery-ui,ruby-on-rails-4

In case anyone is wondering, this is what worked for me in Rails 4: def sort params[:video].each_with_index do |id, index| Video.update(id, position: index+1) end render :queue end ...