ruby-on-rails,model,nested , Rails - is it possible to have a shortcut within a model for its nested attributes?


Rails - is it possible to have a shortcut within a model for its nested attributes?

Question:

Tag: ruby-on-rails,model,nested

This might be a stupid question but it's wracked my head for a while...

So.. I have 2 models: (1) user, and (2) profile. The profile is associated to user via the following relationships:

(1) user has_one :profile
(2) profile belongs_to user

It is the standard relationship for user and profile within the devise system. Anyways, usually I access the user's name through the following nested attributes:

"user.profile.name"

is it possible to create a "virtual" attribute within the user model that links to this attribute within the profile model? I would like to call "user.profile.name" through "user.name".


Answer:

Yes, there is: delegate

class User < ...
  delegate :name, to: :profile

   # The rest of your class
end

This will expose the name method from the Profile class to your User class


Related:


Rails Association Guidance [on hold]


ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2
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...

paper clip show image url is undefine


ruby-on-rails
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...

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


ruby-on-rails,ruby,refactoring
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 menu.name, ("tech/""#{menu.name.parameterize}") %></td> </tr> <% end %> I feel...

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


ruby-on-rails,forms
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...

Active Record Where Clause For Relation In Model


ruby-on-rails,activerecord
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...

Rails - Simple Form - Nested Resources paths


ruby-on-rails,simple-form,simple-form-for
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#,...

Javascript not executing when using link_to


javascript,jquery,ruby-on-rails
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...

Routes work in Development But not in Production


ruby-on-rails,routes
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...

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


ruby-on-rails,email,mailer
On my local host, I followed this article made a mail server and it works well. https://www.digitalocean.com/community/tutorials/how-to-install-postfix-on-centos-6 I want to develop a mailer feature with rails framework. Here are my settings: # mailer config.action_mailer.default_url_options = { :host => 'example.com' } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'localhost', port: 25,...

Rails basic auth not working properly


ruby-on-rails,ruby,authentication
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...

Can Rails deal with DB uniqueness without index?


mysql,ruby-on-rails,rdbms
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...

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


ruby-on-rails,integration-testing
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...

Mongoid HABTM relationships across embedded documents


ruby-on-rails,ruby-on-rails-4,mongoid,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...

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


ruby-on-rails,ruby
I have the following line of code : if params[:"available_#{district.id}"] == 'true' @deliverycharge = @product.deliverycharges.create!(districtrate_id: district.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...

Active Record association links, but can't assign values


ruby-on-rails
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...

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


ruby-on-rails,ruby
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 = (from..to) @mapped_dates = date_range.map {|date| date.strftime("%b %e")} I reference them in some JS in my view as follows: dateLabels = <%= raw @mapped_dates.to_json %>;...

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


ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller
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...

Seeding fails validation for nested tables (validates_presence_of)


ruby-on-rails,ruby,validation,ruby-on-rails-4,associations
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...

Redirect if ActiveRecord::RecordNotUnique error exists


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

How to convert a string into datetime format using rails?


ruby-on-rails
I am getting date and time from datetime picker and I want to store this into database. Database field type= datetime. I am using ruby on rails.

unable to retrieve data from a form in rails


ruby-on-rails
i am trying to access the data from a form. <% form_tag(:action => "test") do %> <p> Name: <%= text_field_tag("name","web programmer") %> </p> <%= submit_tag ("Save data") %> <% end %> this form is in views/challenges/show.html I have written this piece of code in challenges_controller def test @name = params[:name]...

User.id not getting saved in form


ruby-on-rails
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...

rendering the partials in controller after the validation check


ruby-on-rails,ruby-on-rails-4,model-view-controller
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...

Sorting in Ruby on rails


ruby-on-rails,json,sorting
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'])...

mongodb populate method not working


node.js,mongodb,model,populate,auto-populate
Here is my code for models var postSchema = new mongoose.Schema({ created_by: {type: Schema.ObjectId, ref:'User', autopopulate: true }, //should be changed to ObjectId, ref "User" created_at: {type: Date, default: Date.now}, text: String }); var userSchema = new mongoose.Schema({ username: String, password: String, //hash created from password created_at: {type: Date, default:...

Getting a collection via Ajax to show in view


jquery,ruby-on-rails,ajax
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",...

Rails less url path change


ruby-on-rails,ruby,url,path,less
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...

Ruby on Rails - Help Adding Badges to Application


ruby-on-rails,ruby,rest,activerecord,one-to-many
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...

Same enum values for multiple columns


ruby-on-rails,ruby,enums
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...

Stack level too deep because recursion


ruby-on-rails,ruby,ruby-on-rails-4,twitter
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...

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


ruby-on-rails,ruby,rack,multipart
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?...

If statement for search field in Rails


jquery,ruby-on-rails,search,if-statement
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...

Make instance variable accessible through hash in Ruby


ruby-on-rails,ruby,ruby-on-rails-4,activerecord
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 user.name # Accessing attribute 'name' via method user[:name] # Attribute 'name' is accessible via hash as well How to make instance variables accessible through...

Heroku RAM not increasing with upgraded dynos


ruby-on-rails,ruby,ruby-on-rails-3,memory,heroku
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...

Rspec view test with url parameters


ruby-on-rails,unit-testing,testing,rspec,rspec-rails
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...

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


ruby-on-rails,gem,activeadmin
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...

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


ruby-on-rails,activerecord,callback
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...

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


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

How to pass array in rails 4 strong parameters


ruby-on-rails,arrays
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 = Order.new(order_params) if @order.save render :json, @order, status:201, location: [:api, @order] else render :json, { errors: @order.errors...

Heroku rake db:migrate failing - uninitialized constant


ruby-on-rails,ruby,heroku
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...

Allowing some enabled and disabled option on collection_select


ruby-on-rails,ruby
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...

Rails Generates Blank Record Even Input Data


ruby-on-rails,crud
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 = Page.new end def...

NullReference Error while assiging values of Modeltype in MVC View (Razor)


vb.net,razor,model-view-controller,model
I have the following MVC Model: Public Class Employee Public Property EmployeeID As Integer End Class Controller: Namespace Controllers Public Class EmployeeController Inherits Controller Function Details() As ActionResult Dim employee As Employee employee = New Employee employee.EmployeeID = 101 Return View() End Function End Class End Namespace View: @ModelType MVCDemo.Employee...

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


ruby-on-rails,railstutorial.org,minitest,guard
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...

Rails shared controller actions


ruby-on-rails,ruby,ruby-on-rails-4
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...

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


ruby-on-rails,activerecord
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 = current_user.discussions.build({group_id: @group.id})...

Order parent model using children in rails


ruby-on-rails,order,models
I have model product and vote, I need to order products by votes count DESC. product has_many :votes, vote belongs_to :product index_controller.rb def index @products = Product.all end ...

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


ruby-on-rails,arrays,ruby,multidimensional-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....

Showing and editing has_many objects in Rails


ruby-on-rails,ruby-on-rails-4
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...

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


ruby-on-rails,ruby,ruby-on-rails-4
My rails app gives following error: NameError (undefined local variable or method 'fac_allocs' for #): app/models/room.rb:4:in '' app/models/room.rb:1:in '' app/controllers/rooms_controller.rb:3:in 'index' room.rb file class Room < ActiveRecord::Base has_many :bookings has_many :fac_allocs has_many :facs, :through => fac_allocs end ...