Newbie Question - Finding Data Problems - ruby-on-rails-3

This is probably a very basic question but I can't figure out what to do.
I need to find a username from an id in an unrelated view.
In my app, my Orders have many Milestones. Each Milestone has an associated user although there is no relationship between the Milestone model and User model. In my Milestones form, I used the following to grab the user id's and display as a name:
<%= f.input :milestone_user, :as => :select, :multiple => false, :input_html => { :size => 1 }, :label => "", :collection => User.find(:all, :order => "name ASC") %>
However, in my show Milestone view, I can only see an id.
In order to display the name, I was trying something like this in the console to test:
#user = User.where(:id => 2)
But when I run:
#user.name
I get a no method error.
My questions are as follows:
Should I just make the milestones belong to Users as well?
If not, what's the best way to display the username?
-- UPDATE --
I'm totally lost about calling this in my view. If I use the suggestion below:
#user = User.find(2)
Actually what we need is something like:
#user = User.find(:milestone_user)
Where milestone_user is an integer. But that gives me errors. Very confused...
-- UPDATE 2 --
In my index view, I'm actually using table builder to display the information. For simplicity, I've deleted the extra code. My home#index view contains:
<% for milestone in orders %>
<li><%= link_to milestone.name, milestone_path(milestone.id), { 'data-href' => milestone.notes, :class => 'selector' } %></li>
<li><%= #users.name %> </li>
<% end %>
And my home controller:
#milestones = Milestone.all
#users = User.find(params[:milestone_user])

Replace #user = User.where(:id => 2) with #user = User.find(2)
UPDATE 2
The easiest way - remove #users = User.find(params[:milestone_user]) from your home#index method and add correct your view file:
<% for milestone in orders %>
<li><%= link_to milestone.name, milestone_path(milestone.id), { 'data-href' => milestone.notes, :class => 'selector' } %></li>
<li><%= User.find(milestone.user_id).name %> </li>
<% end %>

Related

condition in partial from other controller

I have a model group -> has_many :questions and a question -> has_many :votes
In my my view show, for the controller groups, I have a partial that can display the list of the questions :
<%= render :partial => 'question', :collection => #group.questions.byvote %>
Then I have a link to vote with a style like this :
<%= link_to(question_votes_path(question), :controller => :vote, :action => :create, :method => :post, :id => 'vote') do %>
<%= image_tag("voteUp.png")%>
<%= question.votes_count%>
<%end%>
What I would like to do is make a condition, like :
<% if canvote?%>
… and change the style of the div.
BUT. Making a condition in the group controller can't be made because I need to make my request about the question and not about the group :
Vote.where(:user_id => current_user.id, :question_id => #question.id).first
How can I make it form the other controller group or tell an helper_method in the question controller ?
I think you should use a model method - you can then call it right in the view and do so unobtrusively. The following method will return true if the user has voted on a given question:
User.rb
def voted?(question)
#returns true if vote exists
Vote.exists?(:user_id => current_user.id, :question_id => question.id)
end
You can use it like this:
_question.html.erb
<% if current_user.voted?(#question) %>
#code to use if the user has voted on this question
<% else %>
#code to use if the user has NOT voted on this question
<% end %>

Rails don't show API object if it matches database object

My app pulls in group objects using an API from Meetup.com. These objects don't go into my database. Users can then add a group to their profile, at which point it does enter my database.
When the user logs back into my site, I don't want to show them the group objects from Meetup.com that they've already added to their profile.The shared key here is meetup.com objects have a "group.id" that matches my database "group" model's "group_id"
If the groups from the API were database objects, I imagine I could do something like this:
#groups = RMeetup::Client.fetch(:groups, :lat => #user.latitude, :lon => #user.longitude)
#justnewgroups = #groups.where("id NOT IN (?)", current_user.groups.pluck(:group_id)
But I don't know how to do it without using where. Maybe something like this in the view?:
<% #groups.each do |group| %>
<% unless group.id == current_user.groups.pluck(:group_id) %>
<%= render :partial => 'groups/group', :locals => { :group => group } %>
<% end %>
<% end %>
I'm not getting any errors, but none of the user's groups are being excluded.
new_groups = RMeetup::Client.fetch(:groups, :lat => #user.latitude, :lon => #user.longitude)
current_group_ids = current_user.groups.pluck(:group_id)
#groups = new_groups.reject { |group| current_group_ids.include?(group.id) }

Memory (hex) address being returned instead of value in Rails

I'm definitely a bit of a noob, so this might be something simple that I'm overlooking, however, the searches that I've done to try and find a solution have come up empty.
I've built a form using formtastic that has 5 input fields: two are text boxes and three are select lists.
<%= semantic_form_for #player do |f| %>
<%= f.inputs do %>
<%= f.input :firstname, :label => "First Name " %>
<%= f.input :lastname, :label => "Last Name " %>
<%= f.input :leagueid, :as => :select, :collection => League.all(:order => :leaguename), :label => "League " %>
<%= f.input :team_1, :as => :select, :collection => Team.all(:order => :name), :label => "Team 1 " %>
<%= f.input :team_2, :as => :select, :collection => Team.all(:order => :name), :label => "Team 1 " %>
<% end %>
<%= f.actions %>
<% end %>
What is happening is that the Teams lists work perfectly (the team names are displayed). However, the League list is a different story. All of the entries in the list look like this (with different a different code after 'League:'):
#<League:0x007fe29c406498>
If I use the form to create a Player, it works fine. The correct league ID goes into the database and everything. I just can't figure out why the names of the teams show, while whatever-that-is shows for the league.
Any and all help is appreciated.
When converting objects to String, Ruby will convert them to the memory address like you see unless you provide a to_s method for string conversions. I haven't used formtastic, but I believe adding a to_s method to your League class should cause it to display what you want.
Try adding
def to_s
#name # use whatever you want to be displayed.
end
to the League class.
You could try explicitly specifying the fields that should be used as the text and id within the select list. I believe it would look like.
<%= f.input :leagueid, :as => :select, :collection => Hash[League.all.map { |league| [league.leaguename, league.id] }]
The syntax is crazy. The call to map is returning an array of name/id pairs, like [ ['league1', 1], ['league2', 2] ]. Calling Hash on that converts it to a hash, like {'league1' => 1, 'league2' => 2}. Seems like the select list should use this hash to populate itself.
There's an example of this at http://rdoc.info/github/justinfrench/formtastic, under the Usage section.
:member_name is the solution I think.
<%= f.input :leagueid, :as => :select, :collection => League.all(:order => :leaguename), :label => "League " %>
Will probably work for you as
<%= f.input :leagueid, :as => :select, :member_name => :league, :collection => League.all(:order => :leaguename), :label => "League " %>
My problem was I have a model with a field the same name as the model and I think that confused Formtastic
Example scaffold:
rails g scaffold Countries code:string country:string
rails g scaffold Types title:string description:string
Model:
class Sign < ActiveRecord::Base
attr_accessible :title, :country_id, :type_id
belongs_to :country
belongs_to :type
Form View:
<%= f.input :type %>
<%= f.input :country, :member_label => :country %>
Having a form without the member_label leads to the object id displaying in the select box for countries although the ID is correctly saved. The type select worked perfectly without declaring member_label.
Note that I didn't need to specify :as => :select as formtastic can deduce this from the belongs_to relationship.
Try using :
<%= form.input :league, :member_label => :leaguename %>
This will override the naming convention of the Formtastic Column Select.
Have a look also at : Overriding the Column Name Convention wiki
Hope this helped.

Need to make a link that shows all news after limiting the amount shown in the index

In my index view i have limited the amount of news shown to the 2 newest ones
but i also want to include a link to all the news in the db
in my news controller i have
def index
#news = News.all(:order => "created_at DESC", :limit => 2)
end
and i made another method to give me all the news
def all
#news_all = News.all(:order => "created_at DESC")
end
should i instead limit the amount of posts in the view ?
here is the link i made to show all news
<%= link_to 'All News', all_news_path =>
and my custum route
match "news/all" => "news#all", :as => "all_news"
im gettin the error that NewsController#show cant find news with id="all"
im quite new to ruby and im not sure how to accomplish this :)
UPDATE
I updated my code like Kien suggested
used collection in my route
resources :news do
collection do
get 'all'
end
end
my index link to all news
<%= link_to 'All news', all_news_path, :class => 'btn btn-mini btn-success' %>
and i have an all.html.erb view
<% #news_all.each do |news| %>
<h2><%= news.title %></h2>
<%= news.created_at.strftime("%Y-%m-%d %H:%M") %><br />
<%= truncate(news.body, :length => 450) %><%= link_to ' meira', news %>
<%= news.author %><br />
<% end %>
this worked great yesterday, but today i pulled from git and now i get undefined local variable or method all_news_path on the link in my index file..
can anyone see why ?
ROUTES
root / news#index
all_news_index GET /news/all(.:format) news#all
news_index GET /news(.:format) news#index
POST /news(.:format) news#create
new_news GET /news/new(.:format) news#new
edit_news GET /news/:id/edit(.:format) news#edit
news GET /news/:id(.:format) news#show
PUT /news/:id(.:format) news#update
DELETE /news/:id(.:format) news#destroy
If you make route like that, it will conflict with show route:
news/:id
news/all
The route will misunderstand all is :id parameters.
You should use collection:
resources news do
collection do
get 'all'
end
end
You will get route: all_news_path. You also need to make a template all.html.erb in your app/views/news folder, to display all news.
Is this your typo? <%= link_to 'All News', all_news_path =>
It's should be <%= link_to 'All News', all_news_path %>

How to access one model within another model in Rails..?

I have one data model 'object' with fields->object_id, object_name.
That is: http://localhost:3000/objects/
I have created another model 'front_pages' (not created any migration in this, instead I have created some pages like 'search.html.erb'(by hand) and the associated controllers).
That is: http://localhost:3000/front_pages/
My question is: How to access/search the items stored in the 'object' database within the 'search.html.erb'.
"These two are in the same rails project folder"
-> How to display the search results into an HTML.erb file?
views/static_pages/show.html.erb
<% #npsobject.each do |npsobjects| %>
Nps:
Nps type:
Nps name:
|
Static_page Controller
class StaticPagesController < ApplicationController
def show
#npsobject=Npsobject.find(:all, :conditions => ['nps_name LIKE ?', "%#{params[ :search]}%"]);
end
views/static_pages/new.html.erb
<%= form_tag( { :action =>"show"}, { :method => "get"}) do %> # The action path is ok??
<%= text_field_tag :search, params[:search], :class => 'inputBox' %>
"button") %>
Please verify the above codes and guide me through, as Im new to RoR..:)
You need to move your
#npsobject = Npsobject.find
into show action
and then each it into your views/static_pages/show.html.erb
<% #npsobject.each do |nps| %>
<%= nps.nps_name %>
<% end %>