I'm new to rails and am trying to tackle a problem that I can't seem to
find the right solution for.
I have an existing database that im building a rails app on top of. One
of my columns 'message' is a long string that I would like to be able to
query and split into various attributes to then be able to display each
of those attributes in a view.
I'm trying to implement this into the controller, but don't seem to be
getting any where.
Can you please let me know how I can achieve this within rails?
I don't quite understand exactly what you mean but it sounds to me like
you
want a custom serializer.
Maybe some example information may help
The table in my database has a few different collumns, one of which is
"message". In this column and example message looks like this:
"The [user] is logged in via [hostname]"
When i query the database and get back each of these matching rows, i
would like to be able to split [user] and [hostname] into a user and
host attributes so that i can call those attributes on my view, rather
then have logic in my view that takes the message attribute and breaks
it up for each row.
I assume the square brackets are not in the string, so that a real
string might look like :
"The administrator is logged in via michael-desktop"
?
If so, you'll probably want to play with some string matching methods.
"match" is a good place to start.
class MyModel < AR::Base
# my model has a big string field called "note_details", from
# which I want to extract the username and hostname values
def username
note_details.match(/The (\S*) is logged in via (\S*)/)[1]
end
def hostname
note_details.match(/The (\S*) is logged in via (\S*)/)[2]
end
end
in the view you can access @my_model.username and @my_model.hostname
like any other attributes. If you have any issue with performance, you
could memoize the results, so you only run the .match once.