I have a successful flash notice for when users enter their email and a failure flash notice for when something goes wrong. Both function, but there's a little number under the notice. When I push to heroku, instead of just a number its the entire line of html code showing up under the flash -- <div class='background'> <div class='alert alert-success'>Thanks for staying up to date.</div>
The haml view:
%body
= if flash[:notice]
.alert.alert-success= flash[:notice]
= if flash[:alert]
.alert.alert-danger= flash[:alert]
The controller:
respond_to do |format|
if #lead.save
format.html { redirect_to :back, :notice => 'Thanks for staying up to date.' }
else
format.html { redirect_to :back, :alert => 'Uh oh, there was a problem.'}
end
end
The output
Thanks in advance~!
You need to replace = with -
Use = when you need to display / render the output in html view.
Use - when you just need to evaluate something or assigning something like that
%body
- if flash[:notice]
.alert.alert-success= flash[:notice]
- if flash[:alert]
.alert.alert-danger= flash[:alert]
Related
Ive been trying to wrap my head around this and find a solution but I feel like Ive hit a stump. Im trying to grab the first, second, or third photo from my SQL database and feed it into my bootstrap carousel on my homepage. This is my code for my photos controller:
class PhotosController < ApplicationController
before_action :set_photo, only: [:show, :edit, :update, :destroy]
# GET /photos
# GET /photos.json
def index
#photos = Photo.all
end
# GET /photos/1
# GET /photos/1.json
def show
end
def show_first
#photos = Photo.find(1)
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
def show_second
#photos = Photo.find(2)
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
def show_third
#photos = Photo.find(3)
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
def show_image
#photos = Photo.find(params[:id])
send_data #photos.image, :type => 'image/*',:disposition => 'inline'
end
# GET /photos/new
def new
#photo = Photo.new
end
# GET /photos/1/edit
def edit
end
# POST /photos
# POST /photos.json
def create
#photo = Photo.new(photo_params)
respond_to do |format|
if #photo.save
format.html { redirect_to #photo, notice: 'Photo was successfully created.' }
format.json { render :show, status: :created, location: #photo }
else
format.html { render :new }
format.json { render json: #photo.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /photos/1
# PATCH/PUT /photos/1.json
def update
respond_to do |format|
if #photo.update(photo_params)
format.html { redirect_to #photo, notice: 'Photo was successfully updated.' }
format.json { render :show, status: :ok, location: #photo }
else
format.html { render :edit }
format.json { render json: #photo.errors, status: :unprocessable_entity }
end
end
end
# DELETE /photos/1
# DELETE /photos/1.json
def destroy
#photo.destroy
respond_to do |format|
format.html { redirect_to photos_url, notice: 'Photo was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_photo
#photo = Photo.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def photo_params
params.require(:photo).permit(:title, :medium, :description, :file)
end
end
Ive been looking up and trying to find a good and simple way to accomplish this. And have tried to use the methods like show_first, second, etc. But Im not sure if I am even implementing it right. Would any be able to shed some light on this or at least point me in the right direction? Is the image/* right? Im basically doing my learning on my own and any help and thorough explanation would be awesome and greatly appreciated!
Why not just do it in the show action?
# GET photos/:id
# GET photos/:id.jpg
def show
#photo = Photo.find(params[:id])
respond_to do |format|
format.html {}
format.jpg do
send_data #photos.image, type: 'image/jpeg', disposition: 'inline'
end
end
end
You can then display the photos by:
<% Photo.order(created_at: :desc).limit(10).each do |photo| %>
<%= tag :img, src: path_for(photo, format: :jpg) %>
<% end %>
Having a problem with a select box in my edit view in (Rails 4 Ruby 2.2) App.
the select box looks as follows:
<%= f.select(:primary_type, options_for_select([['RESIDENT - COMPLAINT',
'RESIDENT - COMPLAINT'], ['THEFT', 'THEFT'], ['PROPERTY DAMAGE', 'PROPERTY
DAMAGE'], ['DOORS / WINDOWS BROKEN', 'DOORS / WINDOWS BROKEN'], ['WATER LEAKING',
'WATER LEAKING'], ['FLOODING', 'FLOODING'],['ACCIDENT - PERSONAL INJURY',
'ACCIDENT - PERSONAL INJURY'], ['ACCIDENT - VEHICLE', 'ACCIDENT - VEHICLE'],
['ACCIDENT - OTHER', 'ACCIDENT - OTHER'], ['FENCES / GATES BROKEN', 'FENCES /
GATES BROKEN'], ['SUSPICIOUS ACTIVITY - PERSON', 'SUSPICIOUS ACTIVITY - PERSON'],
['SUSPICIOUS ACTIVITY - VEHICLE', 'SUSPICIOUS ACTIVITY - VEHICLE'], ['VANDALISM -
REPORTING', 'VANDALISM - REPORTING'], ['VANDALISM - IN PROGRESS', 'VANDALISM - IN
PROGRESS'], ['HAZZARD REPORT - SAFETY', 'HAZZARD REPORT - SAFETY'], ['HAZZARD
REPORT - FIRE', 'HAZZARD REPORT - FIRE'], ['FIRE - ACTIVE', 'FIRE - ACTIVE'],
['PARKING COMPLAINT - RESIDENT', 'PARKING COMPLAINT - RESIDENT'], ['PARKING
COMPLAINT - VISITOR', 'PARKING COMPLAINT - VISITOR'], ['BREAK AND ENTER -
ATTEMPT', 'BREAK AND ENTER - ATTEMPT'], ['BREAK AND ENTER - CONFIRMED', 'BREAK AND
ENTER - CONFIRMED'], ['ALARM PANEL - PROBLEMS', ' ALARM PANEL - PROBLEMS'], ['GAS
LEAK', 'GAS LEAK'], ['EXPLOSION', 'EXPLOSION'], ['DAMAGE - WEATHER RELATED',
'DAMAGE - WEATHER RELATED']]), { include_blank: true }, class: 'input-group input-
group-lg', id: 'primary-box')%>
It saves to the DB when selected originally and have confirmed this with Rails Console but have no idea how to get this to display in the select box as the primary value when I go to the edit page.
my controller is as follows:
class CallsController < ApplicationController
before_action :set_call, only: [:show, :edit, :update, :destroy]
# GET /calls
# GET /calls.json
def index
#calls = Call.all
#active_calls = #calls.select{|x| x.status == 'ACTIVE'}
#pending_calls = #calls.select{|x| x.status == 'PENDING'}
end
# GET /calls/1
# GET /calls/1.json
def show
end
# GET /calls/new
def new
#call = Call.new
end
# GET /calls/1/edit
def edit
end
# POST /calls
# POST /calls.json
def create
#call = Call.new(call_params)
respond_to do |format|
if #call.save
format.html { redirect_to #call, notice: 'Call was successfully created.' }
format.json { render :show, status: :created, location: #call }
else
format.html { render :new }
format.json { render json: #call.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /calls/1
# PATCH/PUT /calls/1.json
def update
respond_to do |format|
if #call.update(call_params)
format.html { redirect_to #call, notice: 'Call was successfully updated.' }
format.json { render :show, status: :ok, location: #call }
else
format.html { render :edit }
format.json { render json: #call.errors, status: :unprocessable_entity }
end
end
end
# DELETE /calls/1
# DELETE /calls/1.json
def destroy
#call.destroy
respond_to do |format|
format.html { redirect_to calls_url, notice: 'Call was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_call
#call = Call.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def call_params
params.require(:call).permit(:call_time, :status, :primary_type, :secondary_type, :site, :address, :unit_1, :unit_2, :unit_3, :unit_4, :call_details, :unit_on_scene, :unit_clear, :call_num, :site_id)
end
end
Any help will be much appreciated! Thanks in advance!And if more info is required please let me know and ill put it up here.
If you are asking how to set the default you would follow the answer located in the rails api docs
For example:
<%= f.select(:primary_type, options_for_select([["Text1", "value1"],["Text2","value2"] "value2") %>
Edit:
On the edit page, you should have a variable set in your controller like #call = Call.find(params[:id])
Then in the view you can do:
<%= f.select(:primary_type, options_for_select([<your_values>], #call.primary_type ) %>
Ok so after reading some other posts and diving a bit deeper into this I found the solution and it seems to be working just great.
<%= f.select(:primary_type, options_for_select([['Opt 1', 'Opt 1'],['Opt 2', 'Opt 2']], **:selected => #call.primary_type** )) %>
The call that retrieved and displays the Selected value is between the ** ** Do not add the asterisks to your code..
My goal is to be able to update a saved record when items are de-selected from a collection_select (and then that record is resubmitted.) Thanks in advance for your help!
Details
I've got a form for Newsavedmaps. Newsavedmaps can have many waypoints. Users can select waypoints in a collection_select, and when they save the Newsavedmap, these waypoints are saved to their own database table.
The problem: when users open the Newsavedmap they've saved, I want them to be able to de-select a waypoint. When they save the Newsavedmap again, I want the de-selected waypoint to be deleted.
This is a Rails 2.3X app I'm maintaining, which is why the collection_select uses a different format below.
Model
class Newsavedmap < ActiveRecord::Base
belongs_to :itinerary
has_many :waypoints, :dependent => :destroy
accepts_nested_attributes_for :waypoints, :reject_if => lambda { |a| a[:waypointaddress].blank? }, :allow_destroy => true
end
View
<% form_for #newsavedmap, :html => { :id => 'createaMap' } do |f| %>
<%= f.error_messages %>
<%= f.text_field :name, {:id=>"savemap_name", :size=>30 }%></p>
<%= collection_select :waypoints, :waypointaddress, #newsavedmap.waypoints, :waypointaddress, :waypointaddress, {}, { :multiple => true, :class => "mobile-waypoints-remove", :id =>"waypoints" } %>
<% end %>
Newsavedmaps Controller
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
waypoint = #newsavedmap.waypoints.build
respond_to do |format|
if #newsavedmap.save
flash[:notice] = 'The new map was successfully created.'
format.html { redirect_to "MYURL"}
format.xml { render :xml => #newsavedmap, :status => :created, :location => #newsavedmap }
else
format.html { render :action => "new" }
format.xml { render :xml => #newsavedmap.errors, :status => :unprocessable_entity }
end
end
end
def update
#newsavedmap = Newsavedmap.find(params[:id])
if #newsavedmap.itinerary.user_id == current_user.id
respond_to do |format|
if #newsavedmap.update_attributes(params[:newsavedmap])
flash[:notice] = 'Newsavedmap was successfully updated.'
format.html { redirect_to "MYURL" }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #newsavedmap.errors, :status => :unprocessable_entity }
end
end
else
redirect_to '/'
end
end
Params when creating new record
Parameters: {"newsavedmap"=>{"name"=>"Name of my map", OTHER FIELDS NOT SHOWN ABOVE, "waypoints"=>{"waypointaddress"=>["1600 Pennsylvania Ave NW, Washington, DC 20500", "350 5th Ave, New York, NY 10118"]}}
I think your problem is in correctly built form (and params which come from it).
I suggest to
look at gem cocoon or nested_form
add waypoints_attributes to attr_accessible
implement helpers from gem (from point #1) in your form
And Rails magic should done other job
Another variant (without using gems) (I think much more difficult way!)
You can remove accept_nested_attributes at all and work with your params directly. But in this case you should manage manually all process: correct inserting records, correct destroying them.
In your case it should smth like this (it is not tested!). The example based on your params which posted in the question.
def create
# delete params 'waypoints' it will be manage manually
waypoints = params[:newsavedmap].delete(:waypoints)
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
waypoints.each do |waypoint|
#newsavedmap.waypoints.build(:waypointaddress => waypoint)
end
if #newsavedmap.save
...
end
end
the main troubles will be in method update
def update
# delete params 'waypoints' it will be manage manually
waypoints = params[:newsavedmap].delete(:waypoints)
# find and setup attributes
#newsavedmap = Newsavedmap.find(params[:id])
#newsavedmap.attributes = params[:newsavedmap]
# TROUBLES start here
# destroy not checked (but existed in DB) waypoints
existed_waypoints = #newsavedmap.waypoints
existed_waypoint_addresses = existed_waypoints.map(&:waypointaddress)
new_waypoints = []
waypoints.each do |waypoint|
if existed_waypoint_addresses.include?(waypoint)
# existed waypoint was selected on the form
# find it and add to new_waypoints
new_waypoints << #newsavedmap.waypoints.find_by_waypointaddress(waypoint)
else
# new waypoint was selected on the form
# build it and add to new_waypoints
new_waypoints << #newsavedmap.waypoints.build(:waypointaddress => waypoint)
end
end
# setup new records for waypoints
#newsavedmap.waypoints = new_waypoints
if #newsavedmap.save
# destroy existed but not selected waypoints
(existed_waypoints - new_waypoints).map(&:destroy)
...
end
end
NoMethodError in UsersController#show
undefined method `signed_in?' for #<UsersController:0x5bf3980>
Rails.root: C:/test_app
Application Trace | Framework Trace | Full Trace
app/controllers/users_controller.rb:91:in `signed_in_user'
Request
Parameters:
{"id"=>"1"}
Show session dump
Show env dump
Response
Headers:
None
In Users_Controller
def signed_in_user
redirect_to signin_path, notice: "Please Sign In." unless signed_in?
end
In SessionsController
def signed_in?
!current_user.nil?
end
module SessionsHelper
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
self.current_user = user
end
def sign_out
cookies.delete(:remember_token)
self.current_user = nil
end
def current_user=(user)
#current_user = user
end
def current_user
#current_user ||= user_from_remember_token
end
def signed_in?
!current_user.nil?
end
def create
user = User.authenticate(params[:session][:email],
params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password combination."
#title = "Sign In"
render 'new'
else
sign_in user
flash.now[:error] = "Welcome, #{user.name}"
render 'AdCon'
end
end
def destroy
sign_out
redirect_to root_path
end
private
def user_from_remember_token
User.authenticate_with_salt(*remember_token)
end
def remember_token
cookies.signed[:remember_token] || [nil,nil]
end
end
*EDIT:*************************************************
I'm using the tutorial on:
http://ruby.railstutorial.org/chapters/updating-showing-and-deleting-users # Listing 9.12
Listing 9.12. Adding a signed_in_user before filter.
app/controllers/users_controller.rb
class UsersController < ApplicationController
before_filter :signed_in_user, only: [:edit, :update]
.
.
.
private
def signed_in_user
redirect_to signin_path, notice: "Please sign in." unless signed_in?
end
end
When I included the helper in the SessionsController I received the message
undefined method `signed_in?' for #
Extracted source (around line #9):
<div>
<% if controller.signed_in? %> <----LINE 9
<%= link_to "Sign Out", signout_path, :method => :delete %>
<% else %>
<%= link_to "Sign IN" , signin_path %>
I included the Helper like this:
class SessionsController < ApplicationController
include SessionsHelper
I couldn't get this to work, so I copied the helper methods into SessionsController and the error went away.and now I'm having an issue with 9.12 where signed_in? is an unknown method. and it makes sense because signed_in? is in SessionsController via a helper. can the UserController access that function. I'm new to rails and confused.
thanks for all the feedback
EDIT:******************
Here is the ApplicationController
class ApplicationController < ActionController::Base
protect_from_forgery
include ActionView::Helpers::SessionsHelper
private
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
helper_method :current_user
end
You're declaring your shared methods in the wrong place. signed_in? should be defined inside your ApplicationController, which is the shared base class for all your other controllers. There is, in essence, no way for you to do what you're trying to do. The UsersController can't access your SessionController's methods, nor should it be able to. That isn't how controllers work.
current_user, current_user=, and signed_in? all belong in your ApplicationController, not your SessionsController, because they're shared methods meant to be used by all your controllers which inherit from ApplicationController.
I figured out, I had a sessionhelper file from another project open and I was editing that one instead of the one associated with my current project. Thanks for the help.
Here's what I got in my logs:
Started POST "/video_votes.437?type=up" for 127.0.0.1 at Fri Mar 18 01:11:14 -0700 2011
Processing by VideoVotesController#create as
Parameters: {"authenticity_token"=>"DLyDcc4MJxK7gk4URiyyjvsLLl9hjtDChAyQRGVawKg=", "type"=>"up"}
Completed in 83ms
NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]):
app/controllers/video_votes_controller.rb:3:in `create'
I get this error when I click the button that calls on the create method.
Here's the code in my create method (note that line three is the #video = Video.find(params[:video_vote][:video_id]) line):
def create
#video = Video.find(params[:video_vote][:video_id])
#vote = #video.video_votes.new
if params[:type] = "up"
#vote.value = 1
else
#vote.value = -1
end
if #vote.save
respond_to do |format|
format.html { redirect_to #video }
format.js
end
else
respond_to do |format|
format.html { redirect_to #video }
format.js {render 'fail_create.js.erb'}
end
end
And here's my code for the button in my view that calls the create method:
<div id='voting_div'>
<%= button_to "+1", video_votes_path(video, :type=> "up"), :remote => true %>
<div id='vote_display'>
<p id='votes'><%= pluralize video.vote_sum, 'Votes' %></p>
</div>
<%= button_to "-1", video_votes_path(video, :type=> "down"), :remote => true %>
</div>
What's going on here? How do I fix this error?
You params hash is
{"authenticity_token"=>"DLyDcc4MJxK7gk4URiyyjvsLLl9hjtDChAyQRGVawKg=", "type"=>"up"}
In this hash there is no key called "video_vote" , so when you try to access params[:video_vote][:video_id], because params[:video_vote] is nil. it will throw this error.
Check your routes or if you need to "GET" more values with the button, because your params hash doesn't know about the "video_vote" key.