rails activerecords query, row splitting - mysql

i have some records like this one
"boss/supervisor/employee"
"boss"
"boss/supervisor"
i would like to put all this records in a select input without repeating themselves... here is what i've done already
in my index i did this:
#jerarquy = Jerarquy.uniq.pluck(:name)
so when i get all the records from the column jerarquy:
<select>
<% #jerarquy.each do |jer| %>
<% jer.split('/').each do |j| %>
<option><%= j %></option>
<% end %>
<% end %>
</select>
i do get the data from the database but i think i have to change something in my controller in order to get the information i want in the order i want, for example if i select a boss i want to get /supervisor and /employee too but if i select a employee i want to only get a employee

This is how you would use flatten to convert the fields to a single array and then use .uniq
ary = ["boss/supervisor/employee", "boss", "boss/supervisor"]
ary.map { |string| string.split('/') }.flatten.uniq
=> ["boss", "supervisor", "employee"]
#jerarquy = Jerarquy.uniq.pluck(:name).map { |string| string.split('/') }.flatten.uniq
<select>
<% #jerarquy.each do |jer| %>
<option><%= j %></option>
<% end %>
</select>
However I would say that this code indicates a poor underlying design.
You should be letting the database handle pulling out unique records.

Related

Accessing data with joined table

How can I access this table with activerecord?
https://gyazo.com/1f37f5031c37967459c9bb18052886e9
Normally I just do Singularnameoftable.find(id).whateveriwant.
But for some reason this is not working.
<% #organisation_ids.each do |x| %>
<% #organisationjuridicalform << Organisation.find(x.to_i).juridicalform_id %>
<% end %>
<% #organisationjuridicalform.each do |y| %>
<% #aorgtype << Organisations_organisationtype.find(y.to_i) %>
<% end %>
This gives me following error :
uninitialized constant
ActionView::Base::CompiledTemplates::Organisations_organisationtype
I tried accessing the table using:
Organisation_organisationtype.find
Organisations_organisationtype.find
Organisation_organisationtypes.find
Organisations_organisationtypes.find
But all of them give the same error as if it doesn't know which table I mean.
Is there a special sytax for tables like this? I cannot seem to find anything about it when browsing online.
I need to acces this table in order to find the actual type in this table:
https://gyazo.com/1db9782b1f73e56a50ec660a3c83944c

How do I pass back multiple select box selections to HTML form?

I am using Perl (and Dancer) with HTML to create a form. On my form I have some fields like so:
<input type="text" name="keywords" id="keywords" value="<% keywords | html %>"/>
<select multiple="multiple" id="sentences" name="sentences" size="3"/>
<% IF list_of_sentences %>
<% FOREACH sentence IN list_of_sentences %>
<option value=<% sentence %>/>
<% END %>
<% END %>
</select>
These are, of course, inside their own divisions and there is more code around, but these are the essentials of what I've got.
These are in main.tt which is interacted with using myApp.pm and there are parameters which are passed back and forth (e.g. keywords and list_of_sentences here). The code is set up with two divs, one with the form and the other purely to show the output. When the form is submitted the output shows correctly, but the select field selections are not retained.
So therefore, what I want to do is make it so that the chosen selection(s) from the 'multiple select' are kept selected.
As an example, in my 'input' keywords field I have the value retained because it has been passed back from the .pm file using param("keywords") using template 'main' .... This works with value="<% keywords | html %>" in the html code.
I have tried to do the same for the multiple select using param("sentences"), but this returns a blank field.
To hazard a guess at the problem it is because there is more than one option and maybe because I am getting the options from the .pm file to start with, but I haven't found the solution yet, so any help would be welcome.
You want to use the selected="selected" attribute on the option element. I would suggest passing both the name of the sentence and flag stating if the option should be in the selected state. For example:
<% IF list_of_sentences %>
<% FOREACH sentence IN list_of_sentences %>
<option value="<% sentence.value %>"<% IF sentence.is_selected %> selected="selected"<% END %> />
<% END %>
<% END %>
And use the following data structure for your sentences:
{ value => $value, is_selected => 0|1 }

Is there a best practices/coherent way to update a database field that contains a hash key-value store?

I'm referring to Rails 3.2's Data Store feature, in which there's the option to store key-value stores in a textfield, even if you're using a relational database like MySQL...it works fine when programmatically manipulating the fields.
But what documentation is there to update these fields from a RESTful HTML form? Or is this something that's not recommended at all? That is, the better solution would be to go to NoSQL?
If I understand the question, I think you just need to declare the field name holding the store, and the associated accessors (properties) in the model, like
store :settings, accessors: [ :weight, :length, :color ]
at which point the field works with AR and AREL just like any other, even with forms.
There's very little magic here. The field holds a hash of values; the store declaration lets Rails know that you can reference them like something.weight or something.color, whether reading or writing. Simple and slick. Classic DHH.
although the question is quite old someone else might find it useful, also im pretty new in ruby and rails so there might be a better way to do this.
In the model:
#user.rb
attr_accessible :preferences
store :preferences
then in the form partial:
#views/users/_form.rb
<% #user.preferences.each do |k, v| %>
<% form.fields_for :preferences, #user.preferences[k] do |p| %>
<div class="field">
<%= p.label k %>
<br/>
<%= p.text_field k, :value => v %>
</div>
<% end %>
<% end %>
Now to add some extra fields from the form ive created 2 attr_accessor in the model:
attr_accessible ... , :new_pref_key, :new_pref_val
attr_accessor ... , :new_pref_key, :new_pref_val
then added the 2 new fields on the form
<%= f.label :new_pref_key %>
<%= f.text_field :new_pref_key %>
<%= f.label :new_pref_val %>
<%= f.text_field :new_pref_val %>
on my controller i made a function that check the presence of the new fields and then merge the previous values of the prefs with new ones, like this:
#users_controller.rb
...
new_key = params[:user][:preferences][:new_pref_key]
new_val = params[:user][:preferences][:new_pref_val]
new_preference = {
new_key => new_val
}
current_params = params[:user][:preferences].merge! new_preference
...
done that i return it and pass it to the update_attributes, hope it helped!

How to optimize my activity feed loop (Rails)

I am implementing an activity feed for my application, much like the facebook news feed. Whenever a user does something (creates a post, comments on a post, creates a photo album, comments on a photo) a row is created in an Activities table, which contains user_id, category, and data. Data is a serialized hash that is different for each type of activity (post contains post title and post id, photo comment contains something else, etc). The view then loops through all of the activities and prints something depending on the category of activity. Pretty simple, and it works. The problem is that it's SUPER slow, so I must be doing something wrong. Here's the code:
#activity.rb snippet
def post?
category == "post"
end
def post_comment?
category == "post_comment"
end
def album?
category == "album"
end
def photo_comment?
category == "photo_comment"
end
#controller snippet
#Activity = Activity.all(:order=> 'created_at DESC', :limit=>"5")
#view snippet
<% #Activity.each do |a| %>
<div class="activity_item">
<div class="avatar" style="background-image: url(<%= small_pic_url(a.user)%>) "></div>
<div class="text"> <%= a.user.username %>
<% if a.post? %>
posted <%= link_to a.data["post_title"], post_path(a.data["post_id"]) %>
<% elsif a.post_comment? %>
commented on <%= link_to a.data["post_title"], post_path(a.data["post_id"]) %>
<% elsif a.album? %>
created a <%= link_to "Photo Album", album_path(a.data["album_id"])%>
<% elsif a.photo_comment? %>
commented on <%= link_to "#{a.data["username"]}'s photo", upload_path(a.data["photo_id"])%>
<% end %>
</div>
</div>
<% end %>
I added a user_id index on the activity table, but that didn't seem to do much. Rendering the 5 activity items/avatars takes over 3 seconds, so there must be a better way to handle this.
Do you have an index on created_at? If you don't, that'll be what's slowing you down - MySQL will have to read through every row in your activities table to make sure it got the latest five (this applies to just about anything using an ORDER BY clause).
And a couple more suggestions, but these are minor. Might shave a few milliseconds off, but nothing on the order of three seconds:
Include the user when you select your activities. This'll let you get your activities and their users in a single DB query. :include => :user should do the trick, or there's a Rails 3-style .include(...) method, if you prefer.
I've heard that serialization can be kinda slow. Perhaps you could use a polymorphic association, and then choose what to display based on a.whatever_type?
Hope this helps!

rails helper for select_tag?

I don't get the point how can I do that code with an select helper?
<select name="cube_name">
<% #cube_names.each do |cube| %>
<option value="<%= cube %>" <% if #cube_name == cube %> selected="selected"<% end %>><%= cube %></option>
<% end %>
</select>
I have a list (#cube_names) and want a HTML select box width all values of the list and the default value (param #cube_name) should be selected.
thanks.
The select_tag helper will not auto-set the selected attribute on an item you pass. It just builds the tag. Use something like:
<%= select_tag("id_of_my_tag", #cube_names.map { |cn| "<option#{cn == cube ? " selected='selected'" : ""}>#{cn}</option>" }.join("")) %>
The first parameter is the id of the select tag, the second is a list of options (here built by mapping the cube names to strings, then joining the array into a single string).
You could alternatively use the options_for_select to build the string:
<%= select_tag("id_of_my_tag", options_for_select(#cube_names, cube)) %>