In my Rails 5.1 app i have 2 controllers: home_controller and posts_controller which i created with the scaffold tool, so what i'm doing is rendering the partial _form.html.haml in the index view of my home_controller.rb like this: (by the way i'm using haml)
.top-space
.row.center-xs
.col-xs-8.col-md-10
.row
.col-sm-3.col-lg-2.col-xs-10.top-space
%ul.no-bullets.text-left
%li=link_to "Explore", "#"
%li=link_to "Suggestions", "#"
.col-sm.col-xs-10
=render "posts/form"
#posts
i added remote: true to the form like this:
= form_for #post, remote: true do |f|
- if #post.errors.any?
#error_explanation
%h2= "#{pluralize(#post.errors.count, "error")} prohibited this post from being saved:"
%ul
- #post.errors.full_messages.each do |message|
%li= message
.mdl-textfield.mdl-js-textfield.full-width
= f.text_area :body, class:"mdl-textfield__input", row:3
= f.label :body, "Write something",class:"mdl-textfield__label"
.actions.text-right
= f.submit 'Save',class:"mdl-button mdl-js-button mdl-button--raised mdl-button--colored"
as you can see it has remote: true but when i submit the form it takes me to the show view in my posts_controller,
this is my posts_controller:
def create
#post = current_user.posts.new(post_params)
respond_to do |format|
if #post.save
format.html { redirect_to #post}
format.json { render :show, status: :created, location: #post }
else
format.html { render :new }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
i created a show.js.coffee to show the post created in a <div id="posts"> below the form
$('#posts').append('<%= j render #post %>')
Basically what i want is to show the post created below the form without reloading the page or taking me to show view in my posts_controller.
What am i doing wrong and how can i achieve this?
Try to set your create action like this maybe:
def create
#post = current_user.posts.new(post_params)
respond_to do |format|
if #post.save
format.js
format.html { redirect_to #post}
format.json { render :show, status: :created, location: #post }
else
format.js
format.html { render :new }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
i have just added format.js
Related
Can you help a noob, please?
I have 2 models - Player and Poker Tables, which have has_and_belongs_to_many association. When i try create player i catch error
undefined method `poker_table'
respond_to do |format|
**if #player.save**
format.html { redirect_to #player, notice: 'Player was successfully created.' }
format.json { render :show, status: :created, location: #player }
else
I use checkboxes for mark needed poker tables, here form code:
<% #poker_tables = PokerTable.all %>
<% #poker_tables.each do |poker_table| %>
<div>
<%= check_box_tag "player[poker_table_ids][]", poker_table.id %>
<%= poker_table.name %>
<%= poker_table.actual_time %>
</div>
<% end %>
create method and params
def create
#player = Player.new(player_params)
respond_to do |format|
if #player.save
format.html { redirect_to #player, notice: 'Player was successfully created.' }
format.json { render :show, status: :created, location: #player }
else
format.html { render :new }
format.json { render json: #player.errors, status: :unprocessable_entity }
end
end
end
def player_params
params.require(:player).permit(:email, :poker_table_ids => [])
end
I can create poker table, but couldn't create a player with associated poker tables.
I don't really understand what I'm doing wrong. I studied a lot of resources about this theme, but i can't find answer.
I followed the episode http://railscasts.com/episodes/136-jquery-ajax-revised
and create my cusotm example.
I put the create form in the index, and create a book by remote method
But I have no idea how to put error message in the page.
please give me some example , thanks~
index
<%= render 'form' %>
<p>
<table id='books_tbl' class="table">
<th>id</th>
<th>title</th>
<th>ISBN</th>
<th>sn</th>
<th>price</th>
<th>Functions</th>
<div class="books" id="books">
<%= render #existed_books %>
</div>
</table>
the controller
# POST /books
# POST /books.json
def create
#book = Book.new(params[:book])
respond_to do |format|
if #book.save
format.html { redirect_to #book, notice: 'Book was successfully created.' }
format.json { render json: #book, status: :created, location: #book }
format.js
else
format.html { render action: "new" }
format.json { render json: #book.errors, status: :unprocessable_entity }
format.js
end
create.je.erb
<% unless #book.save %>
<% else %>
$('#books_tbl tr:last').after('<%= j render(#book) %>');
<% end %>
First, change your books_controller so that it will always render create.js.erb whether the book is persisted or not.
def create
#book = Book.new(params[:book])
respond_to do |format|
if #book.save
format.html { redirect_to #book, notice: 'Book was successfully created.' }
format.json { render json: #book, status: :created, location: #book }
else
format.html { render action: "new" }
format.json { render json: #book.errors, status: :unprocessable_entity }
end
format.js
end
end
Then, in you create.js.erb, you will want to check whether your book is persited? or not:
<% if #book.persisted? %>
# ...
<% else %>
# display the error message
<% end %>
Let's say we are going to display the error message in a <p> with the .errors class:
$('<p>').text('<%= #book.errors.full_messages.to_sentence.capitalize %>')
.prepend('form');
The thing is that you will have to remove the errors paragraph every time you render create.js.erb so that former errors won't stick around:
$('p.errors').remove();
All in all, it gives:
$('p.errors').remove();
<% if #book.persisted? %>
# ...
<% else %>
$('<p>').text('<%= #book.errors.full_messages.to_sentence.capitalize %>')
.prepend('form')
<% end %>
I understand how to implement a single has_many association using simple_form, but how do you assign an additional association from another model object?
In my code, I'm creating model object #opportunity. I'm currently assigning a company_id, but also need to assign a 'user_id.
#opportunity _form.html.erb
<% if user_signed_in? %>
<%= simple_form_for([#company, #company.opportunities.build], html: {class: "form-inline"}) do |f| %>
<%= f.error_notification %>
<%= f.input :description, label: false, placeholder: 'Create an opportunity', input_html: { class: "span4" } %>
<%= f.submit 'Submit', class: 'btn btn-small'%>
<% end %>
<% else %>
<%= link_to "Create an Account", new_user_registration_path %>
to contribute
<% end %>
opportunity_controller.rb
def create
#company = Company.find(params[:company_id])
#opportunity = #company.opportunities.create(params[:opportunity])
respond_to do |format|
if #opportunity.save
format.html { redirect_to company_path(#company), notice: 'Opportunity was successfully created.' }
format.json { render json: #opportunity, status: :created, location: #opportunity }
else
format.html { render action: "new" }
format.json { render json: #opportunity.errors, status: :unprocessable_entity }
end
end
end
Assuming that your user is logged in, you can change your controller action to the following:
def create
#company = Company.find(params[:company_id])
#opportunity = #company.opportunities.new(params[:opportunity]) # new instead of create
#opportunity.user = current_user # new
respond_to do |format|
if #opportunity.save
format.html { redirect_to company_path(#company), notice: 'Opportunity was successfully created.' }
format.json { render json: #opportunity, status: :created, location: #opportunity }
else
format.html { render action: "new" }
format.json { render json: #opportunity.errors, status: :unprocessable_entity }
end
end
end
this form (views/workers/_form.html.erb) redirects me to the index of tasksadmins, after I push the 'create tasksadmin' button.
I want it to redirect me to "workers/index" and change the button to 'update the task'.
how can I do that please?
<%= form_for(#tasksadmin) do |f| %>
<% if #tasksadmin.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#tasksadmin.errors.count, "error") %> prohibited this tasksadmin from being saved:</h2>
<ul>
<% #tasksadmin.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :admin_mail, :value => #tasksadmin.admin_mail %>
<%= f.hidden_field :worker_mail, :value => #worker_mail %>
<%= f.hidden_field :task, :value => #tasksadmin.task %>
<div class="field">
<%= f.label :done %><br />
<%= f.check_box :done %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and this is my workers_controller:
class WorkersController < ApplicationController
# GET /workers
# GET /workers.json
def index
#tasks_worker = Tasksadmin.where(:worker_mail => "alon.shmiel#gmail.com")
respond_to do |format|
format.html # index.html.erb
format.json { render json: #workers }
end
end
# GET /workers/1
# GET /workers/1.json
def show
#task_worker = Tasksadmin.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #worker }
end
end
# GET /workers/new
# GET /workers/new.json
def new
#worker = Worker.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #worker }
end
end
# GET /workers/1/edit
def edit
#tasksadmin = Tasksadmin.find(params[:id])
#worker_mail = "alon.shmiel#gmail.com"
end
# POST /workers
# POST /workers.json
def create
#worker = Worker.new(params[:worker])
respond_to do |format|
if #worker.save
format.html { redirect_to "#worker", notice: 'Worker was successfully created.' }
format.json { render json: #worker, status: :created, location: #worker }
else
format.html { render action: "new" }
format.json { render json: #worker.errors, status: :unprocessable_entity }
end
end
end
# PUT /workers/1
# PUT /workers/1.json
def update
#worker = Tasksadmin.find(params[:id])
respond_to do |format|
if #worker.update_attributes(params[:worker])
format.html { render action: "index", notice: 'Worker was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #worker.errors, status: :unprocessable_entity }
end
end
end
# DELETE /workers/1
# DELETE /workers/1.json
def destroy
#worker = Tasksadmin.find(params[:id])
#worker.destroy
respond_to do |format|
format.html { render action: "index" }
format.json { render json: #worker }
end
end
end
In your controller, you have to redirect to the appropriate path like so:
def update
redirect_to "workers/index"
end
I would suggest using path helpers so if you have your routes set up as resources, you can do this:
redirect_to workers_path
As for changing the the button text, just change it to:
f.submit("update the task")
You create a form for an object #tasksadmin, which in your WorkersController#edit is set as follows:
#tasksadmin = Tasksadmin.find(params[:id]
This means that that parameter contains an object of class Tasksadmin, if you let rails build the path for the a Tasksadmin, it will send you to the TasksadminsController#update, and that is why your code does not work. You never get to the WorkersController#update. Check your logs to verify that.
Let me be very clear about this: you should not edit Tasksadmin objects in the WorkersController.
I do not understand why you would do that.
I have a users table (Devise) , with a column "admin" (boolean) to qualify my users.
I also have a namespace "Backend".
I would like that my admins users can create new users from the backend namespace.
So I created a Backend::UsersController :
class Backend::UsersController < ApplicationController
layout 'admin'
before_filter :authenticate_user!
def index
#auteurs = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #auteurs }
end
end
def new
#auteur = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #auteur }
end
end
def create
#auteur = User.new(params[:auteur])
respond_to do |format|
if #auteur.save
format.html { redirect_to #auteur, notice: 'Article was successfully created.' }
format.json { render json: #auteur, status: :created, location: #auteur }
else
format.html { render action: "new" }
format.json { render json: #auteur.errors, status: :unprocessable_entity }
end
end
end
end
Here's the "_form" partial called in the "new" view :
<%= simple_form_for(#auteur) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :email %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
An here's my routes :
namespace :backend do
resources :articles
root to: "articles#index"
resources :accueil
resources :users
get "users/index"
get "users/create"
get "users/new"
end
devise_for :users
But when I try to access to "backend/users/new", it drives me to this error :
NoMethodError in Backend/users#new
Showing C:/Ruby/acturevue/app/views/backend/users/_form.html.erb where line #1 raised:
undefined method `users_path' for #<#<Class:0x39616b0>:0x416f6d0>
Does somebody have any ideas of the source of the problem ?
Thanks
UPDATE
So, I modified my code like that :
In Backend::UsersController :
def new
#user = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #user}
end
end
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
format.html { redirect_to backend_users_path(#user), notice: 'Article was successfully created.' }
format.json { render json: #user, status: :created, location: #user }
else
format.html { render action: "new" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
In _form :
<%= simple_form_for(#user) do |f| %>
But I still have the error.
However the backend_users_path exists in y routes :
backend_users GET /backend/users(.:format) backend/users#
index
POST /backend/users(.:format) backend/users#
create
new_backend_user GET /backend/users/new(.:format) backend/users#
new
edit_backend_user GET /backend/users/:id/edit(.:format) backend/users#
edit
backend_user GET /backend/users/:id(.:format) backend/users#
show
PUT /backend/users/:id(.:format) backend/users#
update
DELETE /backend/users/:id(.:format) backend/users#
destroy
You need to use the namespace in your redirect:
redirect_to [:backend, #auteur] #...
See my answer to this question.