How to use a variable as object attribute in rails?
Reading AR attribute
@payment_detail.send("#{address_type}_address_country")
OR
@payment_detail.read_attribute("#{address_type}_address_country")
Writing AR attribute
@payment_detail.send("#{address_type}_address_country=", value)
OR
@payment_detail.write_attribute("#{address_type}_address_country", value)
Setting instance variable
@payment_detail.instance_variable_set("@#{address_type}_address_country", value)
Getting instance variable
@payment_detail.instance_variable_get("@#{address_type}_address_country")
Reference
- send method documentation
- read_attribute method documentation
- write_attribute method documentation
- instance_variable_get method documentation
- instance_variable_set method documentation
Using variable to access object values like Javascripts object[var] in Ruby
Ruby has more classical heritage, so objects are not extensible in the same way as in JavaScript. Depending on your use case, you would use a hash object or an open struct.
person = {
"name": "John Smith"
}
puts person["name"]
Most of the time you'll see symbols be used instead of string literals.
person = {
:name => "John Smith",
}
puts person[:name]
Finally you could use a struct or open struct if you really want to the same type of semantics as in JavaScript.
person = OpenStruct.new
person.name = "John Smith"
person.age = 70
person.pension = 300
Using a Variable Name as Attribute in Rails
If you want to assign to an attribute, you need the method name with the equal sign:
f.send("#{percent_field}=", 5)
Also, this:
rank_class = (klass.name).constantize
is equivalent to this:
rank_class = klass
Ruby on Rails variables, object attributes, and methods that use a : before or after them
:symbol
{key: value}
When the colon is before the variable / object, it denotes a "symbol", meaning a piece of data to be placed there. The symbol can typically be used in the likes of calling an attribute (key) or in part of a hash: @user.comment[:created_at]
When the colon is after the variable / object, it means you're setting or getting some sort of value in a key: value
pair. {key: value}
pairs are used mostly in hashes, kind of like an array except you can call the specific keys. This is how the attributes of models are invoked in Rails. EG:
@user = {name: "joe", email: "joe@email.com"}
@user.name #-> "joe"
Referencing an object attribute by a string
{
picture: Picture,
picture_for_x: PictureForX,
picture_for_y: PictureForY
}.each do |name,klass|
if !@item.send(name).blank?
copy = klass.new
copy.save!
item_copy.send("#{name}=",copy)
end
end
Remember that in Ruby there are no properties or attributes available externally, just methods (which you may choose to call without parentheses so that it looks like you're accessing a property, and which sometimes might be just returning the value of an instance variable).
Object#send
is the magic method that lets you invoke a method based on a name stored in a variable.
Ruby add variables to an existing object?
To create temporary custom Objects without add new attributes to database Struct solve my problem.
I can create a Struct with chat room info and total users
chat_info = Struct.new(:name, :total_users, :messages)
chat_temp = []
chats = ChatRoom.where(condition)
chats.each do |chat|
chat_temp << chat_info.new("nome", 100, messages)
end
How do I add an attribute to an instance variable in rails 4?
The type of @foo_users
is ActiveRecord::Relation
. Trying to add age_sum
as a new attribute to an ActiveRecord::Relation
object doesn't make sense because semantically age_sum
is not an attribute of ActiveRecord::Relation
objects. It's better to store the sum of ages in a new instance variable, for example @user_age_sum
.
UPDATE
Try the following
class HotelStatistic < ActiveRecord::Base
belongs_to :hotel
end
class Hotel < ActiveRecord::Base
has_many :hotel_statistics
def last_30_days_check_ins
self.hotel_statistics.where("date >= ?", 30.days.ago).sum(:check_ins)
end
end
Keep the existing code for building @recent_stats
in the controller
In the view
<% @recent_stats.each do |statistic| %>
Hotel Id: <%= statistic.hotel_id %>
Daily check-ins: <%= statistic.check_ins %>
Last 30 days check-ins: <%= statistic.hotel.last_30_days_check_ins %>
<% end %>
More elegant way of setting an object attribute dynamically from string in Ruby
You can do
[:@web, :@mobile, :@accessible].each do |stylesheet|
@theme.instance_variable_set(stylesheet, "some dynamic value"))
end
This saves the string concatenation and string->symbole conversion, so theoretically it's should be a bit faster.
Related Topics
How to Customize Rails Activerecord Validation Error Message to Show Attribute Value
Why Is Enumerable#Each_With_Object Deprecated
Rails 4 Nested Attributes Not Saving
Ruby Modulo 3 with Negative Numbers Is Unintuitive
Ruby Array to JSON and Rails JSON Rendering
Ruby Difference in Array Including Duplicates
Rails 3.1 - Has_And_Belongs_To_Many Deprecated
How to Make 'Whenever' Gem Work on Windows
How to Get Last N Records with Activerecord
Ruby on Rails: Delete Multiple Hash Keys
Is There a Way in Ruby 1.9 to Remove Invalid Byte Sequences from Strings
Converting from Xml Name-Values into Simple Hash
Problems Setting a Custom Primary Key in a Rails 4 Migration
Functional Code Examples in Ruby
Sass::Syntaxerror: File to Import Not Found or Unreadable: Compass in Production
Rspec --Init Not Working/ 'Mkd Ir': Invalid Argument - ./C: (Errno::Einval)