ruby-on-rails,ruby-on-rails-4,rails-activerecord,each,collect
.each and .collect are collection methods defined in Enumerable mixin in Ruby, not methods defined in ActiveRecord::Base. In order to call .each or .collect you need a collection object that responds to these method calls. So use: @articles = Article.all.collect{|x| x.publisher == 'Bloomberg'} and, array = [] @articles = Article.all.each...
mysql,ruby-on-rails,ruby,encoding,rails-activerecord
File.read returns a String that will claim to have UTF-8 encoding by default. That means that this: Foo.create(b:File.read('b.jpg')) is really: some_utf8_string = File.read('b.jpg') Foo.create(b: some_utf8_string) But a JPEG will rarely be a valid UTF-8 string so you're going to get that ArgumentError whenever someone tries to treat it as UTF-8....
mysql,sql,ruby-on-rails,rails-activerecord
I may be wrong, but it looks to me that you can easily get rid of the double concat if you rewrite the query to avoid YODA-style from select * from clients where 'Ed Sheeran' like Concat(Concat('%',first_name),'%') or 'Ed Sheeran' like Concat(Concat('%',last_name),'%') to SELECT * FROM clients WHERE first_name LIKE...
ruby-on-rails,ruby,ruby-on-rails-4,rails-activerecord
Since you want a collection of Performers at the end, start with that model. We know we're looking for a specific Venue, so let's see which associations we can use to get there. # Performer has_many :shows, through: :engagements # Show has_many :venues, through: :bookings Bingo! We can go from...
ruby-on-rails,ruby-on-rails-4,activerecord,rails-activerecord
Well the below, Book.where(fiction: true).collect { |book| book.pages } can be written as : Page.joins(:book).where("books.fiction = ?", true) Similar way : Word.joins(page: :book).where("books.fiction = ?", true) ...
ruby-on-rails-4,activerecord,rails-activerecord
This line is syntactically wrong. has_many :project_numbers, through: => :resources #wrong This is the right syntax has_many :project_numbers, :through => :resources # right For Rails4,you can write it to has_many :project_numbers, through: :resources Do the same changes to the other association too....
ruby-on-rails,ruby,rails-activerecord
Dynamic finders are no longer available in the most recent versions of ActiveRecord. Simply use Model.where(full_profile_id: value) where Model is the model name, and value is the value of the full_profile_id attribute....
ruby-on-rails,ruby-on-rails-4,rails-activerecord
Since this is too big to fit into a comment, there you have it as an answer: rows = [ {name: 'Atlanta Falcons', moniker: 'Falcons', city: 'Atlanta', state: 'GA', zipcode: '0', code: 'ATL', conference: 'NFC', division: 'South', primary_color: 'BD0D18', secondary_color: '000000', tertiary_color: 'FFFFFF', quaternary_color: 'DCE0E5', quinary_color: '', weather_location: 'Atlanta+GA+USGA0028:1:US', plays_in_dome:...
ruby,activerecord,orm,rails-activerecord,adventure
To get room.neighbours working, I believe you would first need to change belongs_to :room_dest, foreign_key: "room_dest_id", class_name: "Room", dependent: :destroy to belongs_to :neighbour, foreign_key: "room_dest_id", class_name: "Room" Note that I removed the dependent: option because you probably don't want to destroy Rooms when Exits are deleted. You want dependent: :destroy...
ruby-on-rails,rails-activerecord,rails-console,ruby-on-rails-4.2
You have to do Slot.find_all_by_sheet_id(96) EDIT The above code should have worked. Although I use Rails 4.1.8. Try following as well: Slot.where(:sheet_id => 338) ...
ruby-on-rails,json,postgresql,rails-activerecord
Lets say your example json is in a variable json. Then we can: section_attributes = JSON.parse(json).symbolize_keys # update section section = Section.find_or_create_by id: section_attributes[:id] section.update_attributes! section_attributes.slice(:section_name_fr, :section_number) section_attributes[:questions].each do |question_attributes| # update question question = section.questions.find_or_create_by id: question_attributes[:id] question.update_attributes! question_attributes.slice(:question_fr, :input_type) # update answer...
ruby-on-rails,rails-activerecord
There should be seminar_id as foreign key in Student table So run command -> rails g migration add_seminar_id_to_students seminar_id:integer then do rake db:migrate...
ruby-on-rails,ruby,rails-activerecord
You can use the as_json to restrict the attributes serialized in the JSON response. format.json { render json: @my_objects.as_json(only: [:id, :name]), ...} If you want to make it the default, then simply override the method in the model itself class MyObject def serializable_hash(options = nil) super((options || {}).merge(only: [:id, :name]))...
ruby-on-rails,ruby,activerecord,rails-activerecord
It's unclear where you're calling this code so this might not apply but I'm going to assume you're doing this within a controller. If that's the case, I would recommend the following approach First in your controller, load all the TaskSets and eager-load the associated models def index @task_sets =...
ruby-on-rails,ruby,rails-activerecord
Add the order to the query. @houses = House.page(params[:page]).per(20).order(created_at: :desc) Even better, you should avoid to chain multiple scopes directly in the controller. This approach is very hard to test. Create a custom method. class House < ActiveRecord::Base # ... def self.listing(page) order(created_at: :desc).page(params[:page]).per(20) end end and call it in...
ruby-on-rails,ruby-on-rails-4,rails-activerecord
Many thanks Yan for your help on this one, I have finally managed to resolve my issue and it actually turned out to be really simple. I am posting here in the hope it helps someone else. What I needed to do was add a has_many relation to services through...
ruby,rails-activerecord,ruby-on-rails-4.2
I'm sorry for the poor description of the problem. It seems that the problem was in rails not loading the lib directory where the Exceptions module was placed. I needed to add config.autoload_paths += %W(#{config.root}/lib) To my application.rb file...
ruby-on-rails,rails-activerecord
You are looking for the includes method. You need something like this : recipe = Recipe.includes(:ingredients, :recipeingredients).first this will return the first recipe with all it's associated ingredients and recipe ingredients. ...
ruby-on-rails,ruby-on-rails-4,activerecord,rails-activerecord
Just replace :address_line?condition with a check for one of the filled out fields: validates :address_line_1, presence: true, if: :address_entered?, length: { maximum: 100, minimum: 3 } validates :zipcode, presence: true, if: :address_entered?, length: { maximum: 20, minimum: 4 validates :state, presence: true, if: :address_entered?, validates :country, presence: true, if: :address_entered?,...
ruby-on-rails,ruby-on-rails-4,rails-activerecord,attr-accessor
render json: user, methods: [:score] attr_accessor is alternative for getter and setter method so it is a method and as I have mentioned we can call it as above...
ruby-on-rails,postgresql,activerecord,rails-activerecord,public-activity
Your query without arel will be : PublicActivity::Activity.select("DISTINCT ON(trackable_type, trackable_id) *") .where("(trackable_type = ? and trackable_id IN (?)) or (trackable_type = ? and trackable_id IN (?))", "Lesson", @my_lessons_ids, "Post", @my_post_ids) ...
ruby-on-rails,ruby,integer,rails-activerecord,days
You should break the question done because this is a lot to ask for in one question. Dimitry_N seemed to be on the right track, but you'll need to add some of your logic to the levels model now. Please chat with me if you want to go over the...
ruby-on-rails,ruby,rake,rails-activerecord
The reason I was getting this weird cryptic SQL'ish output is because I had Heroku's rails_12factor gem in my gemfile and not grouped to :production. The solution was to do: group :production do gem 'rails_12factor' end and run bundle...
Here is the solution: ActiveRecord::Batches.module_eval do def find_in_batches2 end end ActiveRecord::Querying.module_eval do delegate :find_in_batches2, :to => :all end Don't forget to implement find_in_batches2....
ruby-on-rails,rails-activerecord
It turns out that validates_associated is ON by default for has_many relationships. To make it conditionally, you'd need to add validate: false to the has_many declaration: has_many :books, validate: false ...
ruby-on-rails,rails-activerecord
Make use of the amazing tool scuttle.io to covert SQL to Arel: Neighborhood.select(:id).where( Arel::Nodes::NamedFunction.new( 'ST_WITHIN', [ Project.arel_table[:lonlat], Neighorhood.arel_table[:the_geom] ] ) ) ...
ruby,ruby-on-rails-4,rails-activerecord
why rails docs says to put inverse_of on a belongs_to relation This is done for memory optimization when fetching associated records. Associated objects do not point to the same in-memory objects by default. Therefore whenever you'll do order.customer without inverse_of on both the :belongs_to and :has_many associations, it will...
ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord
Take a look for ancetry gem it will let you manage parent->children relations with ease.
ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord
First of all has_and_belongs_to_many association names should be plural. Video model: class Video < ActiveRecord::Base has_and_belongs_to_many :topics end Topic model: class Topic < ActiveRecord::Base has_and_belongs_to_many :videos end Then you can use create method added by has_and_belongs_to_many @topicTest= Topic.create!(title: 'Test') @topicTest.videos.create!(title: 'Test') Or @topicTest= Topic.create!(title: 'Test') @topicNew= Topic.create!(title: 'New') video =...
sql,ruby-on-rails,postgresql,activerecord,rails-activerecord
School. joins(:expenses). where("lower(schools.name) LIKE ?", "%a%"). # part of the code you shared where("expenses.cost > ?", 1_000). group("schools.id") ...
ruby-on-rails,ruby,rails-activerecord,grape,grape-entity
In case of belongs_to you need to mention the foreign_key explicitly like this: class Message < ActiveRecord::Base belongs_to :conversation, :class_name => 'Conversation', inverse_of: 'messages', foreign_key: :conversation_id class Entity < Grape::Entity expose :id, :content expose :conversation, :using => 'Conversation::Entity' end end ...
ruby-on-rails,rails-activerecord,rails-models
I think this is a duplicate of Ruby on Rails Double Association For your case use class_name as the second parameter to your belongs_to function and a hash with foreign_key and the id column name (as pointed out by @devkaoru), like so: class Dispute < ActiveRecord::Base belongs_to :claimant, class_name: 'User',...
ruby-on-rails,ruby,rails-activerecord
You may want to give the Amoeba gem a try. Reference: http://stackoverflow.com/a/9485672/336920 Also deep_clonable. They both work with Rails 4 and have been updated recently....
ruby-on-rails,sql-server,rails-activerecord
1) To detect changes, simplest solution is to use EXCEPT Above query/statement INSERT INTO #changes (...) SELECT ... FROM external.dbo.object EXCEPT SELECT ... FROM internal.dbo.object insert into #changes all rows from external.dbo.object that are different or doesn't exist in internal.dbo.object. For sync I would use MERGE statement (see above examples):...
Take an example like you want to find user that have same name and email then try this one and you will get all user that have same name and email and once you get this output delete those User, User.find(:all, :group => :username, :having => "count(*) > 1" )...
ruby-on-rails,coding-style,rails-activerecord
If you are getting the model name as a string. You can do this model_name = "Table1" #or "Table2", "Table3" model = model_name.constantize model.total You can directly turn any string into a class with constantize method. Note - If you are going to use rails further, ideally refer to them...
ruby-on-rails,activerecord,model-view-controller,rails-activerecord,strong-parameters
The params available in your controller are merely the result of the names of the fields in the form in the browser. The names of the fields in the form follow a convention that Rails has created using the form helper functions that you are using in your views. When...
ruby-on-rails,ruby-on-rails-3,activerecord,ruby-on-rails-3.2,rails-activerecord
You could use Arel to perform OR queries or the ActiverecordAnyOf gem. However, in your case, you could just use inclusion (IN statement). For example: .where(period_type: %w(on from), date: Date.today) ...
postgresql,rails-activerecord,materialized-views
ActiveRecord doesn't care whether it is really a primary key in the database or not, but you need to set the primary_key field on your object using the primary_key= method. So something like: class Matview < ActiveRecord::Base self.table_name = 'MATERIALIZED_VIEW_NAME_HERE' self.primary_key = 'ID_COLUMN_NAME_HERE' end ...
ruby-on-rails,ruby-on-rails-3.2,rails-activerecord
Try to use change_table method: change_table(:cad_perfil_niveis) do |t| t.integer :perfil_niveis_nivel_id, :null => false, :default => 1, foreign_key: { references: :cad_perfil_niveis_niveis, on_update: :cascade, on_delete: :restrict }, index: { with: [:id], unique: true, :name => 'unique_perfil_niveis_id_nivel' } end ...
ruby-on-rails,rails-activerecord
You can write as : class FlexField < ActiveRecord::Base has_many :flex_field_values, class_name: 'FlexFieldValue', dependent: :destroy after_save :delete_flex_values def delete_flex_values if self.field_type != 'list' self.flex_field_values.clear end end end A brief idea about collection.clear: Removes every object from the collection. This destroys the associated objects if they are associated with dependent: :destroy,...
ruby-on-rails,rails-activerecord
I think what you're looking for is using a join to find users. User.joins(estates: :location).where(locations: {address: "London"}) This tells your sql call to match users to estates and estates to locations and to select only the users where the location is "London"....
ruby-on-rails,model-view-controller,rails-activerecord,polymorphic-associations
It's a little bit hacky but I found a workaround. So in my CommentsController i did this: def create new_params = comments_params new_params[:user_id] = current_user.id @comment = @commentable.comments.build(new_params) if @comment.save redirect_to @commentable, notice: "Comment created" else render :new end end that placed the user_id which is what I needed....
ruby-on-rails,ruby,ruby-on-rails-4,rails-activerecord,actionview
Member of a FaceBook group helped me figure it out by adding a little extra logic in the controller.. if @campaign.save zip = Uploadzip.find(params[:uploadzip_id]) zip.campaign = @campaign zip.save flash[:success] = "Campaign Successfully Launched!" redirect_to @campaign else flash[:error] = "There was a problem launching your Campaign." redirect_to new_campaign_path end ..which was...
ruby-on-rails,ruby,activerecord,twitter,rails-activerecord
The most direct cause of your problem is that tweets.each will return the tweets array, which since it is not nil or false has a truthy value: you're not using the result of your validate_uniqueness_of method. You instead would want to either do something like tweets.all? { |tweet| validate_uniqueness_of(user,tweet) }...
ruby-on-rails,ruby,rails-activerecord
I think what you want is the ActiveRecord::Base.instantiate method. It will correctly handle the new_record?/persisted? issue, as well as finding the correct class for single-table inheritance. For example: fields = result.fields models = result.values.map { |value_set| Model.instantiate(Hash[fields.zip(value_set)]) } ...
ruby-on-rails,rails-activerecord
This issue has been fixed in rails 4.2. Specifically, if an activerecord instance has a null id, then object_id.hash is used as the hash value....
ruby-on-rails,ruby-on-rails-4,rails-activerecord
This seems like a custom job. Say you have a field named field. validate :no_modifications_on_field def no_modifications_on_field if field_changed? && !field_was.nil? errors.add(:field, 'Once you set a field, you can never change it!') end end field_changed? and field_was are ActiveModel::Dirty helpers that get generated for every field. You can also access...
ruby-on-rails,ruby,rails-activerecord
If misstyping is a problem, keep the column as text, but have it as a select instead of an input tag. You can also validate that column to see it matches the list of states For the list you can have it in a constant to keep it accessible like...
ruby-on-rails,ruby-on-rails-4,rails-activerecord
I think what you're thinking of doing is a Single Table Inheritance, STI. You could have a parent model, ItemMarkdown, or whatever, and that would also be the table in the database. You'd have a field "type" which would be either "MaleItemMarkdown" or "FemaleItemMarkdown" and then Rails would know that,...
ruby-on-rails,activerecord,rails-activerecord
There are 2 ways to solve this: One is like @Alex Pan's answer: using has_and_belongs_to_many The other one is using belongs_to and has_many relation with a junction table. in game.rb: has_many :game_team_maps has_many :teams, through: :game_team_maps in team.rb has_many :game_team_maps has_many :games, through: :game_team_maps in game_team_map.rb belongs_to :game belongs_to :team...
ruby-on-rails,ruby,postgresql,rails-activerecord
ActiveRecord For ActiveRecord, you could put a method like this in your Item class: def self.with_all_categories(category_ids) select(:id).distinct. joins(:categories). where('categories.id' => category_ids). group(:id). having('count(categories.id) = ?', category_ids.length) end Then you can filter your queries like so: category_ids = [1,2,3] Item.where(id: Item.with_all_categories(category_ids)) You could also make use of scopes to make it...
ruby-on-rails,ruby,postgresql,rails-activerecord
What are the limits of using Float in Rails/Postgres? PostgreSQL supports floating point numbers using the identifiers float, real, and double. The identifiers float and real are synonyms. On most computers, float and real will give you at least 6 digits of decimal precision. This is what six digits...
ruby-on-rails,ruby,rails-activerecord
For add foreign key, you add first the name of table (not the model name), this as first parameter, and as second parameter the name of foreign table(not the model name). The table as first parameter should have a column with a name specific as follow: name_foreign_model_id. Example: Foreign model...
mysql,ruby-on-rails,ruby-on-rails-4,order,rails-activerecord
I would place a column on the event for last_activity, and maintain it by touching from the associated models. The alternative is to order by using a join or subquery against the other tables, which is going to require a database query that will be much less efficient than simply...
ruby-on-rails,ruby,rails-activerecord,models,model-associations
Assuming your Job can only have one worker that is set when a Proposal is accepted, you'd want something like this: class Job < ActiveRecord::Base belongs_to :poster, class_name: 'User', foreign_key: 'poster_id' belongs_to :worker, class_name: 'User', foreign_key: 'worker_id' has_many :proposals, dependent: :destroy end class User < ActiveRecord::Base has_many :posted_jobs, class_name: 'Job',...
ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord
In these docs you have: When are Objects Saved? When you assign an object to a has_and_belongs_to_many association, that object is automatically saved (in order to update the join table). If you assign multiple objects in one statement, then they are all saved. If you want to assign an object...
ruby-on-rails,ruby,rails-activerecord,optimistic-locking
You have to initialize all the articles lock_version to 0. Look at the query: UPDATE "articles" SET "title" = 'dwdwd', "updated_at" = '2015-02-25 20:40:36.537876', "lock_version" = 1 WHERE ("articles"."id" = 1 AND "articles"."lock_version" = 0) (0.1ms) If the query returns 0 records updated, then the framework suppose that you have...
ruby-on-rails,ruby,ruby-on-rails-4,model,rails-activerecord
You can load the first medication for a specific user_id like this (assuming that your medications table has a user_id): Medication.where(:user_id => current_user.id).order(:name).first If our User model has a belongs_to :medications it can be simplified to: current_user.medications.order(:name).first If you want to load the e.g. 5th medication just add an offset...
ruby-on-rails,ruby,ruby-on-rails-4,rails-activerecord
The issue with your code is that you are using an instance variable in the context of a class, therefore it will persists as long as the process is running. You need to convert #get to be an instance method, and reuse an instance of the Site class. What you...
ruby-on-rails,ruby,postgresql,rails-activerecord,jruby
Simply fixed the issue by updating database related gems, using the bundle update command.
ruby-on-rails,postgresql,rails-activerecord,atomic,sidekiq
Your Group.increment_counter call sends SQL like this to the database: update groups set tasks_count = coalesce(tasks_counter, 0) + 1 where id = X where X is @task.id. The SQL way to get the new tasks_counter value is to include a RETURNING clause: update groups set tasks_count = coalesce(tasks_counter, 0) +...
ruby-on-rails,rails-activerecord
The Wisper gem is exactly what are you looking for.
ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord
The solution (for the time being...please, oh please keep working...) is specifying class_name: "User" in two of the User model associations: has_many :supervisors, through: :initiated_supervisions, class_name: "User" has_many :supervisees, through: :non_initiated_supervisions, class_name: "User" ...
ruby-on-rails,rails-activerecord,where
id = spree_current_user.supplier.stock_locations .first.stock_location_id Spree::Shipment.where(stock_location_id: id, state: %w[shipped ready]) ...
ruby-on-rails,postgresql,rails-activerecord
I would use another routes: get 'contests/:id/start' => 'contests#start', as: start_contest put 'contests/:id/vote' => 'contests#vote', as: vote Then, in contests_controller/start action def start @contest = Contest.find(params[:id]) random_photos = @contest.photos.limit(2).order("RANDOM()") @photo1 = random_photos.first @photo2 = random_photos.last end In contests_controller/start action def vote @contest = Contest.find(params[:id]) @photo1 = Photo.find(params[:up_photo_id]) @photo2 = Photo.find(params[:down_photo_id])...
ruby-on-rails,ruby,ruby-on-rails-3,rails-activerecord
The first problem I see here is in your associations (and I believe it's the main reason this crap is happening). Your Booking model is a typical joining model for a has_many :through association. But the inner associations are not set properly. If you look at the association between Dog...
ruby-on-rails,ruby-on-rails-4,activerecord,rails-activerecord,database-performance
I don't know of an out of the box rails solution for this so I think it will take some custom code. It should be very straightforward and only involve adding some callbacks to Vote and two cache columns to Content. You can view available callbacks here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html I think...
ruby-on-rails,ruby-on-rails-4,rails-activerecord
That is two functionalities: Overriding the foreign key for an association. This is done with the foreign_key parameter on an association: belongs_to :question, foreign_key: "stack_overflow_id". This will allow you to do instance.association and get the correct records back. Finding a record by parameters, rather than the automatically created ID field....
ruby-on-rails,ruby,postgresql,rails-activerecord
First of all, created_at is a timestamp not a date so you're not grouping by dates at all, you're grouping by date and time of day. This is why you'll get multiple results for some dates. Secondly, you can get the database to do all the work by using a...
ruby-on-rails,ruby,left-join,rails-activerecord
This is probably because of the ID columns of two tables conflicting with one another. Update: Simply changing the order of select columns will help. So instead of .select("questions.*", "answers.*"), try .select("answers.*", "questions.*"). Old answer: Try the following: # Assuming the following: # Question.table_name == "questions" # Answer.table_name == "answers"...
ruby-on-rails-4,rails-activerecord,simple-form,omnicontacts-gem
So what I was trying to do was not possible. Ultimately it took creating an Import Controller so that I could call a nested Controller form through the User model. <div class="row"> <div class="small-12"> <%= simple_form_for(@user, url: import_path) do |f| %> <%= f.simple_fields_for :contacts, @contacts do |contact| %> <%= render...
mysql,ruby-on-rails,postgresql,activerecord,rails-activerecord
You should be able to chain .uniq onto the end of the query to bring back unique records. Or you could try .distinct http://apidock.com/rails/ActiveRecord/QueryMethods/distinct...
ruby-on-rails,rails-activerecord
You can't call set the .personal_info=true on the method itself. In such situation I'd just use either Hashes. def profile_completeness ret = Hash.new if self.name.present? && self.email.present? ret[:personal_info] = true end ret end Or even better I'd prefer different method for each of the 'completeness' part: def personal_info_complete? .... end...
ruby-on-rails,ruby,ruby-on-rails-4,activerecord,rails-activerecord
The escaping just looks wrong in the console when using to_sql, your last example actually sends this to MySQL: SELECT `users`.* FROM `users` WHERE (email REGEXP '[@\\.]gmail\\.com') You can confirm this by running the actual query in the console and checking the log file....
ruby-on-rails,ruby,activerecord,rails-activerecord
You might have to unscope your name condition and add it again: Field.where(name: 'Bukk').unscope(where: :name).where.not(name: 'Tolgy') rewhere uses unscope to do its work anyway....
ruby-on-rails,ruby,sqlite,rails-activerecord
You could use a nested raw SQL query: SELECT AVG(hourly_count) as average_count_all FROM ( SELECT count(*) as hourly_count, date_created_at, hour_created_at FROM ( SELECT date(created_at) as date_created_at, hour(created_at) as hour_created_at FROM tweet ) as hours GROUP BY date_created_at, hour_created_at ) as hourly_counts This is untested, but the idea is this: Parse...
ruby-on-rails,ruby,rails-activerecord
Write it: def self.find_by_search(search) return includes(:question). where("question like ?", "%#{search}%"). references(:question). sort_by { |q| ActiveSupport::Inflector.transliterate(q.question.text) } end Documentation of includes clearly said : conditions: If you want to add conditions to your included models you’ll have to explicitly reference them ...
ruby-on-rails,ruby,ruby-on-rails-4,rails-activerecord,rails-models
Building on mohamed-ibrahim's answer. How about doing it like this? class Project < ActiveRecord::Base attr_accessor :main_color, :secondary_color, :tertiary_color has_many :items accepts_nested_attributes_for :items validates :main_color, :presence => true validates :secondary_color, :presence => true validates :tertiary_color, :presence => true def main_color=(m_color) self.colors ||= [] self.colors[0] = m_color end def main_color self.colors[0] end...
ruby-on-rails,ruby-on-rails-4,devise,rails-activerecord,actioncontroller
For /accounts.ac045b73-8f9c-446f-9cc2-d86b01cea3b7 your app is taking as format ac045b73-8f9c-446f-9cc2-d86b01cea3b7 but your controller only knows how to handle html and json. You should verify why /users/sign_in is redirecting to that weird link...
ruby-on-rails,rails-activerecord
From here it appears to be done using an SQL in statement: Model.where('id IN (?)', [array of values]) Or more simply, as kdeisz pointed out (Using Arel to create the SQL query): Model.where(id: [array of values]) ...
ruby-on-rails,rails-activerecord
class Photo < ActiveRecord::Base has_and_belongs_to_many :photosets validates_uniqueness_of :flickr_uid end class Photoset < ActiveRecord::Base belongs_to :user validates_uniqueness_of :flickr_uid has_and_belongs_to_many :photos belongs_to :primary_photo, class_name: 'Photo' end ...
ruby-on-rails,ruby,postgresql,ruby-on-rails-4,rails-activerecord
You can specify foreign keys like so: In a belongs_to belongs_to :parent, foreign_key: 'parent_alphanum_id', primary_key: 'uniq_alphanum_identifier' Or a has_many has_many :children, foreign_key: 'parent_alphanum_id', primary_key: 'uniq_alphanum_identifier' Then Rails should just work as usual....
ruby-on-rails,postgresql,rails-activerecord
So the answer is to call .load on the query. QuestionSubmission.joins(:rubric_item_evaluations).where(:rubric_item_evaluations `=> {:present => true , :rubric_item_id => @rubric_item.id}).load Collection proxies are lazy evaluated and only run sql queries when it needs to. So in order to actually execute the query on the variable assignment (e.g. eagerly), simply call .load....
ruby-on-rails,rails-activerecord
I figured it out, all I needed to do was to remove the attr_accessor line completely. Rails 4 uses strong parameters when it comes creating an ActiveRecord object, although in my case I'm only showing it so I do not need it.
ruby-on-rails,ruby-on-rails-3,ruby-on-rails-4,rails-activerecord
I'm not sure I understand the problem 100% correctly but I think you're looking for something like: ["12-d", "50 cent", "ACDC", "Mr Cool"].group_by{ |artist| ((artist =~ /[0-9]/) ? "numbers" : artist[0]) } which would return: {"numbers"=>["12-d", "50 cent"], "A"=>["ACDC"], "M"=>["Mr Cool"]} ...
ruby-on-rails,database,sqlite3,rails-activerecord,normalization
For your business logic, creating table 'addresses' could be good, because in future your users can have more then 1 address. From sql point you should make new table addresses but I am against building your tables because some rule of normalizing your db model. In your case address will...
ruby-on-rails,activerecord,internationalization,yaml,rails-activerecord
se: common: &common name: "Namn" activerecord: attributes: user: <<: *common town: "Stad" admin: <<: *common level: "Nivå" pet: <<: *common company: <<: *common food: <<: *common ...
ruby-on-rails,rails-activerecord
Why dont you use to https://github.com/rails-api/active_model_serializers to serialize the object as per your need. Its handy and very helpfull. And use respond_with and respond_to insted for format.json You can create serializer as class AccountSerializer < ActiveModel::Serializer attributes :name, :method_name, :instane_method_name def method_name "value" end end and in controller respond_with @accounts,...
ruby-on-rails,rails-activerecord,has-many-through,model-associations,rails-postgresql
subscribed_tags - it's a scope (where(user: self)), you can call where or join on them but not an item methods. In your case you want to use a scope class Card scope :with_subscription, -> { joins(tags: :subscriptions) } end # In controller current_user.cards.with_subscription.order('cards.created_at DESC') You can imagine current_user.cards like another...
mysql,ruby-on-rails,ruby,rails-activerecord,sql-injection
Use Post.attribute_names to take columns of Post model then just check that columns contains your field_name and raise error if it doesn't contains.
ruby-on-rails,postgresql,activerecord,rails-activerecord,rails-migrations
Rails itself only supports a limited set of constraints. You can run arbitrary SQL commands through execute, though: class CreateAddresses < ActiveRecord::Migration def change create_table(:addresses) do |t| t.string :phone_number, null: false end execute "ALTER TABLE addresses ADD CONSTRAINT addresses_phone_length CHECK (length(phone_number) = 11)" end end ...
ruby-on-rails,activerecord,rails-activerecord
The problem here is that the joins will return the same user multiple times, if the user has more than one tracking log. You can use uniq to get each user only once: User.joins(:tracking_logs).where(created_at: Time.now-1.day..Time.now).uniq.size See also here: http://guides.rubyonrails.org/active_record_querying.html#joining-a-single-association...