How do I join and display first_name with last_name? - ruby-on-rails-3

I am using devise and cancan with rails 3.2.1 and I'm having an unusual problem that I know can be refactored and simplified, but after much searching, I'm stuck.
I have first_name and last_name fields in the user model and have successfully displayed the full name of the user in the users/show.html.erb view using this code:
<%= #user.first_name + " " + #user.last_name %>
And I was successfully displaying a link to the user's show page in the header using:
<% if user_signed_in? %>
<li><%= link_to #user.first_name + " " + #user.last_name, current_user %></li>
<% end %>
But, and I can't figure this one out, after working on another part of the app, the header started giving me an undefined method error message...
In any case, I know there is a much better way to define and work with user names and I have tried some things out, such as adding a name method to the user model, but as you can clearly tell from this post, I am a beginner and have not been able to make that work.
Please let me know if you have any ideas on how to best work with users names in an application like this.

Where are you defining #user? I'm willing to bet that it's in your UsersController show action, which means it's defined for your header in that action only.
Try replacing your header code with this:
<% if user_signed_in? %>
<li><%= link_to current_user.first_name + " " + current_user.last_name, current_user %></li>
<% end %>
The trick is that Devise makes current_user always available when the user is signed in. You don't have to worry about setting a #user instance variable.

Related

Rails sessions stored in database

I have a page that shows a list of events. When the event is clicked it takes you to a login page and it keeps the session id along with the page. When I go to the next page it always sends the last session variable.
<% #events.each do |e| %>
<%= link_to e.event_name, sessions_new_path %>
<%= e.event_start %> - <%= e.event_stop %>
<% session[:event_id] = e.id %>
<%= session[:event_id] %>
<br>
<% end %>
This shows the session[:event_id] is there and it is storing in the variable but when I click on the link it will send the last session[:event_id] of the loop. Any ideas would be helpful. I am looking at option of either passing the variable to the next page or storing it into a database cell, but not sure on how sessions are stored in databases.
Assuming you are using a supported database with ActiveRecord, you can configure your application to store sessions in the database by editing your_app/config/initializers/session_store.rb:
YourApp::Application.config.session_store :active_record_store
make sure to comment out or remove the line:
# YourApp::Application.config.session_store :cookie_store, :key => '_your_app_session'
Further, there are auth gems that handle redirecting users to protected pages after signing in. If you haven't already, look at Devise and/or authlogic. Personally, I prefer Devise.

Editing multiple records at once - how to update without IDs

Still new to Rails. I'll try to provide as much detail as possible.
I have a form that lets me update multiple records at one time.
It's based off the 'Editing Multiple Individually' Railscast episode.
<%= form_tag(auction_clerk_path(#auction), :method => :put) do %>
<% #lots.each do |lot| %>
<%= fields_for "lots[]", lot do |f| %>
<%= f.number_field :sale_price %>
<% end %>
<% end %>
<% end %>
(Simplified to just include a single input for each instance)
An Auction contains multiple Lots (items for sale).
The auction_clerk_path is the route I'm using to just show all lots on one auction.
Everything is working just fine... until I use try to customize my lot paths...
I've added the following to my lot.rb file to be able to use:
/auctions/:auction_id/lots/:lot_number
instead of /auctions/:auction_id/lots/:id
def to_param
lot_number
end
So, in the form mentioned earlier, the fields render with name="lots[12][sale_price]" where 12 is the id.
However with the to_param change, now the fields render with name="lots[1][sale_price]" where 1 is the lot_number.
When I save, the submitted parameters are lot_numbers instead of ids.
So obviously when it tries to update, it won't find the correct records.
My method definition looks like this:
def save_clerking
#updated_lots = Lot.update(params[:lots].keys, params[:lots].values).reject { |l| l.errors.empty? }
if #updated_lots.empty?
flash[:notice] = "Lots updated"
redirect_to auction_clerk_path(#auction)
else
render :action => "clerk"
end
end
I either need to change my method definition to lookup by lot number, or change the form to somehow output IDs in the first place... but I don't know how.
Any help is appreciated. Thanks!
Fixed this through some help on another question.
I changed my method def to
#updated_lots = []
params[:lots].each do |lot_number, attributes|
lot = Lot.where("lot_number = ? AND auction_id = ?", lot_number, params[:auction_id]).first
if lot.update_attributes(attributes)
#updated_lots << lot
end
end
You could fetch the ids by lot number in the controller action and feed those to the update method instead of the params keys.

Rails 3 - how with declarative_authorization test, if user is admin?

In the documentation I found this part:
<% permitted_to? :create, :employees do %>
<%= link_to 'New', new_employee_path %>
<% end %>
This is good, but I need to test, if the current user is admin, and if does, so then display some text... Something like
if admin?
I can get this information from associations, like:
if current_user.role == 0
but this is a bit dirty solution... support Declarative Authorization some cleaner and nicer way to do it?
This is what I have been looking for:
if has_role?(:admin)
...
end

How do I make a settings configuration page for the rails-settings gem?

I just discovered the rails-settings gem and now I need to make an admin page that lets me edit the setting values. How would I make a settings controller with an edit view that can change these dynamic app wide settings?
I haven't used this gem but it seems like it should be fairly straight forward. Since it uses a database backed model, you would simply create a controller as normal:
rails g controller Settings
From here you would define your index action to gather all your individual settings for display in the view:
def index
#settings = Settings.all
end
Then in the view you can setup a loop to display them:
<% #settings.each do |setting| %>
<%= setting.var %> = <%= setting.value %>
<% end %>
As far as editing ... this might be a bit tricky since by default rails would expect you to submit only one setting at a time to edit. You could do it this way but unless you implement the edit with ajax it might be tedious and non-intuitive.
Another way would be to set up your update method to accept all the individual settings at once, loop through and update each one with new values. It might look something like this:
// The /settings route would need to be setup manually since it is without an id (the default)
<%= form_tag("/settings", :method => "put") do %>
<% #settings.each do |setting| %>
<%= label_tag(setting.var, setting.var) %>
<%= text_field_tag(setting.var, :value => setting.value) %>
<% end %>
<%= submit_tag("Save Changes") %>
<% end %>
This should output all of the settings (given they have been assigned to the #settings variable) with the var name as the label and the current value as the text field value. Assuming that the routing is setup, when you submit this form the action that receives it should all the new settings in the params variable. Then you can do something like this in the action:
def update
params.each_pair do |setting, value|
eval("Settings.#{setting} = #{value}")
end
redirect_to settings_path, :notice => 'Settings updated' # Redirect to the settings index
end
This may not be the best way depending on how often you edit the settings and how many settings you have...but this is a possible solution.
I was looking for some suggestions for this and found another answer to this that is very simple and elegant, for anyone looking for this later. It just sets up dynamic accessors in your model, allowing your form to have settings fields just like your normal attributes. An example can be found in the original answer:
How to create a form for the rails-settings plugin

Pull friends uid using fb_graph

does anyone know how to pull a list of facebook friends uid using fb_graph? My current code is below but it does not work. I'm using devise and omniauth.
In my user controller
def profile
profile ||= FbGraph::User.me(self.authentications.find_by_provider('facebook').token).fetch
end
In my view
<% current_user.profile.friends.each do |friend| %>
<%= friend.uid %>
<% end %>
I've been looking for solution for days but still in vain and will appreciate if anyone could tell me the clue.
Use friend.identifier instead of friend.uid.