I'm new to rails,Any clues ? and it would be better if you can suggest me what to read as well.
Im adding a date picker plugin into an existing rails4 app. i found this plugin on Github. i followed the instruction and configured everything in my app. Visiting http://localhost:3000/bookings/new looks fine, but after i fill up the information and submit it , error occurs :
ArgumentError in BookingsController#create
First argument in form cannot contain nil or be empty
booking_controller.rb:
def new
#booking = Booking.new
end
def create
#booking = current_user.bookings.build(booking_params) # Not the final implementation!
if #booking.save
flash[:success] = "You have submited the information successfully!"
redirect_to root_url
else
render 'static_pages/home'
end
end
new.html.rb
<%= form_for (#booking) do |f| %>
<%= render 'shared/errorbooking_messages' %>
<%= f.label :date_of_tour %>
<input data-provide="datepicker">
<%= f.label :hotel_name %>
<%= f.text_field :hotel_name, class: 'form-control' %>
<%= f.label :hotel_address %>
<%= f.text_field :hotel_address, class: 'form-control' %>
Replace this input field
<input data-provide="datepicker">
by
<%= f.text_field :date_of_tour, "data-provide" => 'datepicker' %>
Hope it's helpful.
Just to build on this answer. As of rails 4 you can also use the following format.
<%= f.text_field :date_of_tour, data:{ provide:'datepicker' } %>
Related
I've been writing a new RoR app for practice. This is a basic app that is supposed to function as a lookup page for animals.
I've been working on the Create/New functions in the controller for my page. I would like to make it so that a user can enter in an animal, and have the animal save to the SQL database. Afterwards, the page should redirect to the newly created animal page.
Here's my animals_controller.rb:
class AnimalsController < ApplicationController
def index
#animals = Animal.all
end
def show
#animal = Animal.find(params[:id])
end
def new
end
def create
# render plain: params[:animal].inspect
#animal = Animal.new(animal_params)
#animal.save
redirect_to #animal
end
private def animal_params
params.require(:animal).permit(:name, :scientific_name, :range)
end
end
Here is my views/animals/new.html.erb:
<h1> Add Animal </h1>
<%= form_for :animal, url: animals_path do |f| %>
<p>
<%= f.label :name %> <br>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :scientific_name %> <br>
<%= f.text_field :scientific_name %>
</p>
<p>
<%= f.label :range %> <br>
<%= f.select :range, ['land', 'sea', 'sky', 'underground'], :prompt => 'Select One' %>
</p>
<p>
<%= f.submit %>
<p>
<% end %>
When I try to enter in a new animal, here is what I get:
<ActionController::Parameters {"name"=>"cat", "scientific_name"=>"Felis catus", "range"=>"land"} permitted: false>
I'm wondering why I keep getting "permitted:false" when I have code in animals_controller.rb that states that these params are permitted! Can anyone point out anything or give me some suggestions?
Your params should look like
<ActionController::Parameters {"animal" => {"name"=>"cat", "scientific_name"=>"Felis catus", "range"=>"land"} } permitted: false>
Also, in the form, can you change :animal to #animal.
Alternatively, you can try this
params.require(:animal).permit(:name, :scientific_name, :range).permitted?
Problem is with this line render plain: params[:animal].inspect
because you are printing/accessing params directly without permission instead use :animal_params
render plain: animal_params.inspect
this lines #animal = Animal.new(animal_params) is fine. I guess your creating process works perfectly only.
I have an issue with an ajax form I use for rendering errors, but it's allowing the user to submit basically an unlimited number of time as long as they keep mashing the submit button. What happens is when the user presses the submit button, it grays out for a fraction of a second with the disable_with text and then becomes clickable again. The user can then keep pressing and making post requests. Only when the user stops does the redirect happen. I've searched through basically all the answers for this particular problem, and they don't seem to work for me. I was wondering if someone could help.
I've tried using javascript to disable the button and using data: {disable_with: "..."}.
Here is my .html.erb code right as of now:
<div class="container-fluid main-container">
<%= form_for [#group, #task], remote: true do |f| %>
<%= f.label :name %>
<%= f.text_field :name, class: "form-control" %>
<%= f.label :description %>
<%= f.text_area :description, class: "form-control" %>
<%= f.label :priority %>
<%= f.text_field :priority, class: "form-control" %>
<%= f.label :user %>
<%= f.select :user_id, options_for_select(#group.options_for_user), {}, class: "form-control" %>
<%= f.submit "Create Task", class: "btn btn-primary new-task-button", data: {disable_with: "Creating task..."} %>
<% end %>
</div>
And here is my controller code for the task new and create actions
def new
#group = Group.find(params[:group_id])
#task = Task.new
end
def create
new_user = User.find(task_params.delete(:user_id))
#task = Task.new(to_update)
respond_to do |format|
if #task.save
#group.tasks << #task
new_user.tasks << #task
format.html {redirect_to #group}
TasksChannel.broadcast_to(#group, {action: "create", data: #task, user: new_user})
else
#errors = #task.errors
format.js {render :file => "layouts/errors.js.erb"}
end
end
end
def task_params
return params.require(:task).permit(:name, :description, :priority, :user_id)
end
I've been stuck on this for a while and it's so frustrating. I would greatly appreciate any help.
Check that the html in your page has that attribute. Open your browser at localhost:3000 and open the developer toolbar to check that html element.
Write some Jquery in your applicationscript.js file and test if the problem is solved. Maybe there is some conflict with turbo-links or something else
$('#my-button').prop('disabled', true);
Disabling button after disable_with
Test the effect also on a simple jquery project without ruby on rails..
I am trying to build a log in system by this tutorial:
http://www.youtube.com/watch?v=h0k6DFIStFY
My form looks like this:
<!DOCTYPE html>
<div id="content">
<%= flash[:alert1] %>
<%= form_for(:sessions, :url => sessions_path , :html => {:id => "login-form"}) do |f| %>
<fieldset>
<p>
<%= label_tag :name ,"Username:" %>
<%= text_field_tag :name, params[:name] , :class => "round full-width-input", :autofocus=>true %>
</p>
<p>
<%= label_tag :password, "Password:" %>
<%= password_field_tag :password, params[:password], :class => "round full-width-input" %>
</p>
<%= submit_tag "Login", :class=> "button round blue image-right ic-right-arrow" %>
</fieldset>
<% if (flash[:status] == FALSE) %>
<br/><div class="information-box round"><%= flash[:alert] %></div>
<% end %>
<% end %>
</div> <!-- end content -->
and my controller looks like this:
class SessionsController < ApplicationController
def login
end
def create
user = User.authenticated?(params[:sessions][:name], params[:sessions][:password])
flash[:alert1] = "dummy"
if user
redirect_to '/login'
else
flash[:status] = FALSE
flash[:alert] = "Invalid username and password"
redirect_to '/login'
end
end
def new
end
end
when trying to submit, i get this error:
undefined method `[]' for nil:NilClass
in the following line:
user = User.authenticated?(params[:session][:name], params[:session][:password])
Did i use incurrectly in the session key ?
Thanks,
Gal!
I think you have some problems in your form: you are using a form_for and then in fields you are using text_field_tag.
I would correct it in something like :
<% form_for sessions .... do |f| %>
<%= f.text_field :name %>
and so forth.
This will generate the params you want in your controller
params[:sessions][:name]
params[:sessions][:password]
I would suggest you to use some gem instead of building an entire system of authentication, which can be quite tricky in terms of security. Have you taken a look at https://github.com/plataformatec/devise?
Hope it helps
It looks like you're using an external authentication gem, perhaps one of these?
https://www.ruby-toolbox.com/categories/rails_authentication
You need to include a require <gem_name> line at the top.
I have two forms that I want to be submitted from new.html.erb, which is served by status_updates Controller. The init form, and the the stat form.
When I submit the stat form, everything works perfectly.
The init form has a different controller it answers to. The problem is that when I submit this form it immediately tries to find the object for the stat form within the controller for the init form.
If I go to that controller and provide the an instance of the object, it'll submit both forms.
Here's the error when I submit the init form.
undefined method `model_name' for NilClass:Class
<div id='stat'>
<%= form_for(#status_update) do |f| %>
The stat form submits fine. When the init form is submitted it tries to process the stat form as well. If I provide the model #status_update within init's action controller it will submit both forms. If not, it throws the above error.
Here's the code for init form
<div id='init'>
<%= form_for(current_user, method: :put ) do |f| %>
<%= f.label :target_bf_percent %>
<%= f.text_field :target_bf_pct %>
<%= f.label :Deficit_percent %>
<%= f.text_field :deficit_pct %>
<%= f.label :activity_factor %>
<%= f.select( :activity_factor, options_for_select(
[['Pick One', nil],
['Sedentary (Desk Job)', 1.2],
['Light Activity (1-3 day a week)', 1.35],
['Moderate Activity (3-5 days a week)', 1.55],
['Very Active ( 6-7 days a week)', 1.75],
['Extremely Active (Atheletic Endurance)', 1.95]]) )
%>
<%= f.submit "Post", class:"btn btn-large btn-primary" %>
<% end %>
</div>
And the code for the stat form
<div id='stat'>
<%= form_for(#status_update) do |f| %>
<%= f.label :current_weight %>
<%= f.text_field :current_weight %>
<%= f.label :current_bf_pct %>
<%= f.text_field :current_bf_pct %>
<%= f.submit "Post", class:"btn btn-large btn-primary" %>
<% end %>
The status_update controller new action:
def new
#status_update = current_user.status_update.build if user_signed_in?
end
The users controller update action:
def update
if current_user.update_attributes!(params[:user])
flash[:success] = "Your personal settings have been saved!"
render new_status_update_path
else
flash[:error] = "Whoops! There was an error saving your personal settings. Please try again."
render new_status_update_path
end
end
Please let me know of anything I can do to improve this question.
It doesn't matter if you render one or more forms on the same page.
Your problem is caused by #status_update because it is nil, but you already know that.
Double check if it is initialized in your controller.
Rails 2.3.11
I would like to use a text_field to input data under one condition, otherwise using a selection box. Right now, my code looks like this:
views/posters/new.html.erb
<% form_for #poster, :html => {:multipart => true} do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :image %> - We're not going to enlarge it for you, so please upload the biggest copy you can!<br />
<%= f.file_field :image %><br />
</p>
<p>
<% if current_user.admin? && params[:event_id] && !current_user.events.find_by_id(params[:event_id]) && Event.find_by_id(params[:event_id]) %>
<%= f.label "Event ID" %><br />
<%= f.text_field :event_id, :value => params[:event_id] %>
<% else %>
<%= f.label :event_id %><br />
<%= f.select :event_id, #events, :selected => params[:event_id].to_i %>
<% end %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
controllers/posters_controller.rb
def new
#poster = Poster.new
current_user ||= User.find_by_id session[:user_id]
#events = [["Don't attach to an event", '']]
current_user.events.each {|event| #events << [event.title, event.id]}
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #poster }
end
end
Error message: http://cl1p.net/halp
How can I use two different types of form input fields for the same parameter (but each under a different condition, not simultaneously)?
Update: I think the problem stems from the issue of Rails putting the previously-submitted information back into their respective input fields. This explains why no tantrum is thrown when a file that passes all the validation tests (that is, a PNG less than 3 MB), but breaks down when nothing (or anything that doesn't meet that condition) is attached.
Firstly, I don't understand why you are manually setting the values on the text box and select box. Usually, Rails does this for you, but without the form definition, I can't tell if you really need to do this.
Even then, given the information, I think it's safe to say that what you need is this:
f.text_field :event_id
...
f.select :event_id, #events
This ought to work for what you intend to do. I'm not sure what it has to do with the submitting of a file, but yes you are right about the previously-submitted part. The unexpected nil stems from this:
params[:event_id].to_i
Unless you are setting this parameter entry manually inside your controller, you will not be able to cast it to an integer if it is nil. If you go with using the basic form helper calls this goes away.