I collect tags in a nice javascript UI widget. It then takes all the tags and passes them to the server as tag1,tag2,tag3,etc in one text_field input. The server receives them:
params[:event][:tags] = params[:event][:tags].split(',') # convert to array
#event = Event.find(params[:id])
Is there a better way to convert the string to the array? It seems like a code smell. I have to put this both in update and in the new actions of the controller.
you could do this in the model:
I have seldom experience on mongoid. The following would work in active record (the only difference is the write_attribute part)
class Event
def tags=(value_from_form)
value_from_form = "" unless value_from_form.respond_to(:split)
write_attribute(:tags, value_from_form.split(','))
end
end
On the other hand, for consistency, you may want to do the following:
class Event
def tags_for_form=(value_from_form)
value_from_form = "" unless value_from_form.respond_to(:split)
self.tags = value_from_form.split(',')
end
def tags_for_form
self.tags
end
# no need to change tags and tags= methods. and tags and tags= methods would return an array and accept an array respectively
end
In the first case (directly overwriting the tags= method), tags= accepts a string but tags returns an array.
In the second case, tags_for_form= and tags_for_form accepts and returns string, while tags= and tags accepts and returns array.
I just create another model attribute that wraps the tags attribute like so:
class Event
def tags_list=(tags_string)
self.tags = tags_string.split(',').map(&:strip)
end
def tags_list
self.tags.join(',')
end
end
In your form, just read/write the tags_list attribute which will always accept, or return a preformated string. (The .map(:strip) part simply removes spaces on the ends in case the tags get entered with spaces: tag1, tag2, tag3.
PeterWong's answer misses the '?' from the respond_to() method;
class Event
def tags=(value_from_form)
value_from_form = "" unless value_from_form.respond_to?(:split)
write_attribute(:tags, value_from_form.split(','))
end
end
Related
I have a column in Company, that is serialized as Array:
class Company
serialize :column_name, Array
end
In rails console, when I try the following:
existing = Company.last.column_name
# it gives a array with single element, say [1]
existing.delete(1)
# now existing is []
Company.last.update_attributes!(column_name: existing)
# It empties the array, so:
Company.last.column_name #gives []
But, when I try the same code in remove method of some controller, it never removes the last element. It always returns [1].
How can I empty the serialized column?
NOTE:- This logic works when I have multiple elements, but doesn't work for the last element alone.
CONTROLLER CODE
def remove_restricted_num
company = Company.where(id: params[:id]).first
restricted_numbers = company.restricted_numbers
num = params[:num].to_i
if restricted_numbers.include?(num)
restricted_numbers.delete(num)
company.update_attributes!(restricted_numbers: restricted_numbers)
render js: "alert('#{num} was removed')"
else
render js: "alert('Number not found in the list')"
end
end
I got the fix, we need to use dup to get a independent variable existing, which otherwise was referencing Company.last.column_name
existing = Company.last.column_name.dup # THIS WORKS!!!
existing.delete(1)
Company.last.update_attributes!(column_name: existing)
This updates the column to [], as I need.
Assume we have a rails params hash full of nested hashes and arrays. Is there a way to alter every string value (whether in nested hashes or arrays) which matches a certain criteria (e.g. regex) and still keep the output as a params hash (still containing nested hashes arrays?
I want to do some sort of string manipulation on some attributes before even assigning them to a model. Is there any better way to achieve this?
[UPDATE]
Let's say we want to select the strings that have an h in the beginning and replace it with a 'b'. so we have:
before:
{ a: "h343", b: { c: ["h2", "s21"] } }
after:
{ a: "b343", b: { c: ["b2", "s21"] } }
For some reasons I can't do this with model callbacks and stuff, so it should have be done before assigning to the respective attributes.
still keep the output as a params hash (still containing nested hashes arrays
Sure.
You'll have to manipulate the params hash, which is done in the controller.
Whilst I don't have lots of experience with this I just spent a bunch of time testing -- you can use a blend of the ActionController::Parameters class and then using gsub! -- like this:
#app/controllers/your_controller.rb
class YourController < ApplicationController
before_action :set_params, only: :create
def create
# Params are passed from the browser request
#model = Model.new params_hash
end
private
def params_hash
params.require(:x).permit(:y).each do |k,v|
v.gsub!(/[regex]/, 'string')
end
end
end
I tested this on one of our test apps, and it worked perfectly:
--
There are several important points.
Firstly, when you call a strong_params hash, params.permit creates a new hash out of the passed params. This means you can't just modify the passed params with params[:description] = etc. You have to do it to the permitted params.
Secondly, I could only get the .each block working with a bang-operator (gsub!), as this changes the value directly. I'd have to spend more time to work out how to do more elaborate changes.
--
Update
If you wanted to include nested hashes, you'd have to call another loop:
def params_hash
params.require(:x).permit(:y).each do |k,v|
if /_attributes/ ~= k
k.each do |deep_k, deep_v|
deep_v.gsub!(/[regex]/, 'string'
end
else
v.gsub!(/[regex]/, 'string')
end
end
end
In general you should not alter the original params hash. When you use strong parameters to whitelist the params you are actually creating a copy of the params - which can be modified if you really need to.
def whitelist_params
params.require(:foo).permit(:bar, :baz)
end
But if mapping the input to a model is too complex or you don't want to do it on the model layer you should consider using a service object.
Assuming you have a hash like this:
hash = { "hello" => { "hello" => "hello", "world" => { "hello" => "world", "world" => { "hello" => "world" } } }, "world" => "hello" }
Then add a function that transforms the "ello" part of all keys and values into "i" (meaning that "hello" and "yellow" will become "hi" and "yiw")
def transform_hash(hash, &block)
hash.inject({}){ |result, (key,value)|
value = value.is_a?(Hash) ? transform_hash(value, &block) : value.gsub(/ello/, 'i')
block.call(result, key.gsub(/ello/, 'i'), value)
result
}
end
Use the function like:
new_hash = transform_hash(hash) {|hash, key, value| hash[key] = value }
This will transform your hash and it's values regardless of the nesting level. However, the values should be strings (or another Hash) otherwise you'll get an error. to solve this problem just change the value.is_a?(Hash) conditional a bit.
NOTE that I strongly recommend you NOT to change the keys of the hash!
I want to create a helper method that can turn the results of a Rails find into a sentence, where I specify the the results, and the column to use for making the sentence. For example:
def items_to_sentence(items, label_column)
items.map { |u| u.(label_column) }.to_sentence
end
I'm just not sure how to tell Rails to use my specified column.
Thanks for looking.
If items contains ActiveRecord objects (or any other objects that have accessor methods that match up with your column names), then you could use send:
def items_to_sentence(items, label_column)
items.map { |u| u.send(label_column) }.to_sentence
end
Or equivalently:
def items_to_sentence(items, label_column)
items.map(&(label_column.to_sym)).to_sentence
end
Or, if that's too noisy:
def items_to_sentence(items, label_column)
sym = label_column.to_sym
items.map(&sym).to_sentence
end
I have a MongoMapper model and am trying to convert a comma-delimited string into an Array to be stored.
The main problem is that a string such as tags = "first,second,third" is not getting converted to an array in the database like ["first","second","third"]. Instead it is going in as ["first,second,third"].
There are some other strange things going on as well:
1) In preen_tags I have to include the unless tags.nil? after every line
2) in preen_tags, using the debugger tags returns nil
Here is my model
class Template
include MongoMapper::Document
validate :validate_tags
after_validation :preen_tags
key :template_id, ObjectId
key :title, String
key :description, String
key :tags, Array
timestamps!
def validate_tags
errors.add_to_base "You Must Enter At Least 1 Tag." if tags.blank?
end
def preen_tags
#return if tags.nil? #why doesn't this work??
#only alphanumeric chars allowed, except hyphens and commas
tags = tags[0] if tags.is_a?(Array)
tags = tags.gsub(/[^0-9a-z\-\,]/i, '') unless tags.nil?
#convert spaces to hyphens
tags = tags.gsub(/\s/, '-') unless tags.nil?
tags = tags.split(",") unless tags.nil?
end
end
it's because by default tags is an Array in MongoMapper like you define it. So you can try tags.empty? instead of tags.nil?
In last case tags becomes nil because you try get first element of tags, but there are no one inside. Just nil. You tags becomes nil.
Looks like converting the String to an Array inside the controller before passing it to the Model has solved things.
I am trying to use a time_select to input a time into a model that will then perform some calculations.
the time_select helper prepares the params that is return so that it can be used in a multi-parameter assignment to an Active Record object.
Something like the following
Parameters: {"commit"=>"Calculate", "authenticity_token"=>"eQ/wixLHfrboPd/Ol5IkhQ4lENpt9vc4j0PcIw0Iy/M=", "calculator"=>{"time(2i)"=>"6", "time(3i)"=>"10", "time(4i)"=>"17", "time(5i)"=>"15", "time(1i)"=>"2009"}}
My question is, what is the best way to use this format in a non-active record model. Also on a side note. What is the meaning of the (5i), (4i) etc.? (Other than the obvious reason to distinguish the different time values, basically why it was named this way)
Thank you
You can create a method in the non active record model as follows
# This will return a Time object from provided hash
def parse_calculator_time(hash)
Time.parse("#{hash['time1i']}-#{hash['time2i']}-#{hash['time3i']} #{hash['time4i']}:#{hash['time5i']}")
end
You can then call the method from the controller action as follows
time_object = YourModel.parse_calculator_time(params[:calculator])
It may not be the best solution, but it is simple to use.
Cheers :)
The letter after the number stands for the type to which you wish it to be cast. In this case, integer. It could also be f for float or s for string.
I just did this myself and the easiest way that I could find was to basically copy/paste the Rails code into my base module (or abstract object).
I copied the following functions verbatim from ActiveRecord::Base
assign_multiparameter_attributes(pairs)
extract_callstack_for_multiparameter_attributes(pairs)
type_cast_attribute_value(multiparameter_name, value)
find_parameter_position(multiparameter_name)
I also have the following methods which call/use them:
def setup_parameters(params = {})
new_params = {}
multi_parameter_attributes = []
params.each do |k,v|
if k.to_s.include?("(")
multi_parameter_attributes << [ k.to_s, v ]
else
new_params[k.to_s] = v
end
end
new_params.merge(assign_multiparameter_attributes(multi_parameter_attributes))
end
# Very simplified version of the ActiveRecord::Base method that handles only dates/times
def execute_callstack_for_multiparameter_attributes(callstack)
attributes = {}
callstack.each do |name, values|
if values.empty?
send(name + '=', nil)
else
value = case values.size
when 2 then t = Time.new; Time.local(t.year, t.month, t.day, values[0], values[min], 0, 0)
when 5 then t = Time.time_with_datetime_fallback(:local, *values)
when 3 then Date.new(*values)
else nil
end
attributes[name.to_s] = value
end
end
attributes
end
If you find a better solution, please let me know :-)