Can't figure out how to display similar field entires - ruby-on-rails

I have been learning rails for a while now, but I still have a lot to learn. I recently found this community and I love it. But now, I am at a loss of what to do.
On the genre/show.html.erb page, I want to display other matching genre.title on this page.
From my understanding I should be able to do this from the show page.
This code of course does not work, and I am sure I am off in the wrong direction, if someone could get me back on path, I would be a happy person.
<% if #genre.title == #genre.title %>
<% #genres.each do |genre| %>
<%= link_to genre.title, movie_genre_path(#movie, genre) %>
<% end %>
This is my route:
movie_genre GET /movies/:movie_id/genres/:id(.:format) genres#show

You can filter your genres in your controller.
def show
movie_genre = Movie.find(params[:movie_id]).genre
#genres = Genre.where(genre: movie_genre)
end
If you use your correct database names in this above code, you will have #genres be what you wanted it to be.

Related

Ruby on Rails: Check_boxes for each item in a list

I'm trying to render simple check_boxes in a list of results so users can select on which of these results to get additional content for.
Example model setup (names changed):
UserRequest has_one :response
Response has_many :individual_results
IndividualResult has_one :contact_info
In the UserRequestsController I have a show action, which shows the user_request (duh), response, and its individual_results in a table.
The user should be able to select items (= contact_info) to request additional content for those. For some reason I don't manage to render the check_boxes after days of trying. Basically, I don't really understand where and how to store the array of selected contact_infos and how to pass it to the method that then gets the additional content.
My attempt was:
Create a ContactInfosController (didn't exist before, the user was only creating and showing her requests up to now, so contact_info was "model only" before)
Create a method request_content(contact_infos) (as post, to pass the user-selected contact_infos to. If I were to make it Restful, it would probably be "edit/update")
Add the form with check_boxes search_request#show
My search_request/show.html.erb:
<tbody>
<% if #response %>
<% form_for #contact_infos, url: contact_infos_request_content_path(#contact_infos) do |form| %>
<% #response.individual_results.each do |result| %>
# result.foo, ...
# result.contact_info.bar
<%= form.check_box "contact_info", "contact_info.request_content?", "true", "false %>
<% end %>
# form.submit
<% end %>
<% end %>
</tbody>
As it didn't work, I also had to declare the instance variable #contact_infos in RequestsController#show as #contact_infos = #response.individual_results.map { |r| r.contact_info }
Now, it fails at the check_box with "undefined method `merge'". Also, not sure how the params would be passed? I feel I went seriously "off the rails" and probably screwed up the design with this as it seems way too complicated...
Would anybody be so kind and help me get into the right direction, e.g., how would you pass the response to a method to request additional information? Read tons online but somehow couldn't apply it.
Thanks so much!

Building a selectbox or filter in Rails

Hi maybe this is a fool question, but i really try to look couldnt find any relevant info, (maybe cause i dont know where exactly to start looking at) ..
I need to build a select box with options so the user can "filter" by the candidate.poisition value i have. at this moment the view has this code..
I was thingin on using :params, to post them in URL (i have always do php, im doing rails cause my task now is to insert a design, i achieve everything, just missing a selectbox filter)
Anyway.. here is the code.. wich is pretty simple
<% #candidates.each do |candidate| %>
<% if (candidate.active == true) && (candidate.position.present?) %>
All the html code with info.. like
<%= candidate.name %> : <%= candidate.position? ? t('generales.'+candidate.position) : t('activerecord.models.elite') %>
<% end %>
<% end %>
how can i make this , as im really a noob in Rails, im a regular user on PHP not even really good jaja, pls, i hope someone can give me a hand on this.
Can I use something like this : How to do a LIKE query in Arel and Rails?
Like candidates.where("position like '%?%'", params[:query]).to_sql
Also how can i build the Post as you do in PHP , no idea, to change the position that you want to filter.
Model Candidate.rb just have this inside :S
class Candidate < ActiveRecord::Base
end
Basically you're right. Here is improved code:
<% #candidates.each do |candidate| %>
<% if candidate.active && candidate.position.present? %>
<%= candidate.name %> : <%= t("generales.#{candidate.position}") %>
<% end %>
<% end %>
Update per request in comments:
Use code like this in controller:
if params[:position] == 'red'
#candidates = #candidates.where(position: 'red')
elsif params[:position] == 'blue'
#candidates = #candidates.where(position: 'blue')
else
#candidates = Candidate.all
end
and build html form that will pass parameter position.
or you can use https://github.com/activerecord-hackery/ransack

Rails - showing comments in a different area

Im trying to create a system which allows athletes to respond to their coaches traing plan, to do this i have allowed the coach to create contentsm however i am using a blogging based system to create it... at the moment the page displays like so
CONTENT TITLE
Content info 1...
Content info 2...
Content info 3...
COMMENTS...
comment 1
comment 2
comment 3
.etc
However i want to set it so that there can only be 7 Comments Max per post as well as set out like this per post...
CONTENT TITLE
Content info 1...
comment 1
Content info 2...
comment 2
Content info 3...
comment 3
.etc
I realise this is probably not the best way to do want i want, but it works (just dosnt appear in the place i want it to)
I did do experiments with creating more models, but kept getting errors whenever i tryed to run more than 1 comment system per post. I was wondering if i could have some help in sorting this out, or any methods i could do to make this easier, or even better if the models would work and if i was just doing something wrong?? tell me if this isn't enough information to go off, and ill try provide some more! Thankyou
.
.
EDIT:
The models i have used are
Program - As in the training plan set for the week
Coaches - The coach that is inputing the data to the rider
Riders - To comment on the coaches data with their own data.
I am unsure what files are need exactly so i have included the link to the github page i am pushing to ( https://github.com/effectonedesign/coacheasy1 ), if there is any other info needed, please let me know!
I like what "mind" has said however, i have done everything have said, in my def show (program controller) it is saying there is an error and i keep getting this message undefined method `coaches' for nil:NilClass everything is identical to his but im getting issues, i really do appreciate the help! Thanks
I would probably create 3 models for the above, TrainingPlan, Section (or content, text_block etc.) and Comment.
Then do the following
TrainingPlan has_many :sections
Section belongs_to :training_plan
Section has_one :comment (if you allow only 1 comment per section, otherwise use has_many)
Comment belongs_to :section
Now, to achieve the formatting you wanted do the following in your views:
<% #training_plan.sections.each do |section| %>
<%= section.text %>
<%= section.comment.text %>
<% end %>
If you allow multiple comments:
<% #training_plan.sections.each do |section| %>
<%= section.text %>
<% section.comments.each do |comment| %>
<%= comment.text %>
<% end %>
<% end %>
Form for comments
I haven't tested the following, so you might need to tweak some parts.The training plan controller:
def show
# using includes will query the database 3 times only (once for each table) rather than
# querying it 1 + N + N (in this case 7 sections, 7 comments possibly, so 15 times)
#training_plan = TrainingPlan.includes(:sections, sections: :comment).find(params[:id])
#sections = #training_plan.sections
#sections.each do |section|
# only build a new comment if there is no comment for that section already
section.build_comment unless section.comment
end
end
In your view views/training_plans/show.html.erb
<%= #training_plan.title %> # or whatever
<% #sections.each do |section|
<%= #section.content %>
<% if section.comment %>
<%= section.comment.content %>
<% else %>
<%= render 'comments/form', comment: section.comment %> # or wherever you have the form
<% end %>
<% end %>
views/comments/_form.html.erb
# This might break if you have a separate comment action somewhere which passes an
# instance variable #comment to the form
<%= form_for comment do |f| %>
# normal form stuff
<% end %>
If that all works then on your training plan show page you should see each section, and if it has a comment then that comment will be rendered, otherwise a form will be shown.
Depending on your routes you might need to run rake routes and see where your comment create action is, and then pass that to the form <%= form for comment, url: some_url_helper_here do |comment| %>
If it was me I would create the add comment part through JavaScript, sort of like in this railscast, but since you're new to RoR I've tried to keep it simple.

How to display a tag cloud from Acts as Taggable On on an index page in Ruby on Rails 3.2.7?

I'm very new to Ruby on Rails, so there's probably a simple solution I'm missing.
The tldr version - how do I display an Acts As Taggable On tag cloud of distinct (i.e. no repeating) tags assigned to all instances of a particular model on that model's index page?
The longer version - I have a model called Video in which I have successfully managed to implement a tagging feature using Acts as Taggable On and this fantastic tutorial.
What I'd like to do now is, on the Video's index page (index.html.erb), to display a summary of all the individual tags that a user has assigned to individual videos. For example, lets say I have three videos, each tagged as follows:
Video 1: great, banana, book
Video 2: small, great, apple
Video 3: rubbish, small, banana
I'd like the index page to display the following list of tags:
great, banana, book, small, apple, rubbish.
The code for my model (elided) is as follows:
class Video < ActiveRecord::Base
attr_accessible :tag_list # Lots of other fields in here as well, but not relevant
acts_as_taggable_on :tags
end
The code in my Video helper is as follows:
module VideosHelper
include ActsAsTaggableOn::TagsHelper
end
Finally, as per the gem's documentation, I've added the following code to my controller:
class VideosController < ApplicationController
def tag_cloud
#tags = Video.tag_counts_on(:tags)
end
end
So, what code should I be adding to the index page of my view? I tried the following, again as per the documentation:
<% tag_cloud(#tags, %w(css1 css2 css3 css4)) do |tag, css_class| %>
<%= link_to tag.name, { :action => :tag, :id => tag.name }, :class => css_class %>
<% end %>
But this returns the following error when I go to the Video index page:
undefined method `empty?' for nil:NilClass
As I say, I'm obviously missing something simple, but I'm completely new to Rails (and Ruby) so I'm still finding my feet.
OK, after hacking about a bit, I think I've found a solution, in case anyone else wondering how to do this happens to stumble across this question.
However, please be aware that I am very much a beginner at RoR, so this is probably not the best solution - if I'm doing anything wrong, or if you have a better solution, feel free to let me know!
Add this code in your view to display the list of tags for a particular model in order:
#tags = ActsAsTaggableOn::Tag.all(:order=>'name')
<% if #tags.count > 0 %>
<ul>
<% #tags.each do |tag| %>
<li><%= link_to tag.name, tagged_url(:tag => tag.name) %></li>
<% end %>
</ul>
<% else %>
<p>There are no tags on the system.</p>
<% end %>
This results in a very basic display and, due to my inexperience I advise using this approach with caution - I'm sure it's not the best, or even the "safest", method, so beware!

Rails Check if User Id is in Array

I'm trying to build a condition based on wether or not a "user" is a "member". Basically I need a way of checking if the current_user.id matches any of the user_id of any members. The non-working code I have right now is:
<% if current_user = #page.members %>
you can view this content.
<% end %>
I'm looking for something along the lines of: "If current_user.id exists in the "user_id" of any members."
Something like this, based on the field names in your question:
<% if #page.members.map(&:user_id).include? current_user.id %>
You can view this content
<% end %>
Assuming your #page.members variable contains an array, you can use the include? method:
<% if #page.members.include? current_user %>
you can view this content.
<% end %>
If you're using an array of ids, you will of course need to change the test slightly to look for the current user's id:
<% if #page.members.include? current_user.id %>
you can view this content.
<% end %>
#member_ids = #page.members.map{|m| m.id()}
then check for the condition as below
#memeber_ids.include? current_user.id()
Has said before include? should do the thing.
I'm just answering to tell you about a gem called CanCan, that gives you easy access for authorization "helpers".
Why you should use CanCan instead of doing what you are actually doing?
Don't reinventing the weel most of the times it's a goob practice.
You are placing business logic on the view (bad practice).
CanCan most likely has been developed thinking on security, and all the best practices in mind.
You save some developing hours.
Sorry if I repeated myself.

Resources