I have a form that is adding rows to the DB via remote => true. I then want to append the new data to a table, but cannot get the correct view to render.
As of now, it is rendering the entire show.html.erb page for the new entry, but I want to layout a minimal version to be added as a . Is there a quick way to tell my controller what view to render after inserting into the db? I want to render my partial named _newly_added.html.erb
My Controller
def new
#task = Task.new
render :partial => "/tasks/newly_added", :locals => { :t => #task }
end
Thanks!!
EDIT
I think what I need is just an alternative "show" view.
I found that the method I needed to change was actually this:
def create
#task = Task.new(params[:task])
respond_to do |format|
if #task.save
format.html { redirect_to #task, notice: 'Task was successfully created.' }
format.json { render json: #task, status: :created, location: #task }
else
format.html { render action: "new" }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
I just need to make an alternative show view, and then tell this to redirect_to that view.
Edited per the changes in your question. However, nothing really changes. You're thinking about things wrong, and need to adjust how you're thinking. You don't need an alternative show, you need to handle the format.js request.
The partial should be rendered within a JavaScript response, not the controller. The controller looks more like this:
def create
#task = Task.new(params[:task])
respond_to do |format|
if #task.save
format.html { redirect_to #task, notice: 'Task was successfully created.' }
format.json { render json: #task, status: :created, location: #task }
format.js
else
format.html { render action: "new" }
format.json { render json: #task.errors, status: :unprocessable_entity }
format.js
end
end
end
Then, in views/tasks/create.js.coffee
($ '#mytable').append("<%= j render(partial: 'tasks/newly_added', locals: { t: #task }) %>")
What's going on here is that the browser makes a call to create.js. The controller responds with the create.js template, because of the respond_to block's format.js. The j escapes the contents of the _newly_added.html.erb file, and the contents of it are appended to the table. The controller doesn't interact with the existing view, instead, JavaScript is sent to the browser, and it interacts with the view.
This all changes somewhat if you're using a client-side MVC framework like Backbone or Ember, but you didn't specify that so I'm assuming you're going with stock Rails.
Related
I am trying to use the standard create method created for Ruby/Rails projects and simply pass in an additional form field that tells the method how many objects to create (vs just creating one object). The standard create method looks like so:
def create
#micropost = Micropost.new(micropost_params)
respond_to do |format|
if #micropost.save
format.html { redirect_to #micropost, notice: 'Micropost was successfully created.' }
format.json { render :show, status: :created, location: #micropost }
else
format.html { render :new }
format.json { render json: #micropost.errors, status: :unprocessable_entity }
end
end
end
I want to pass in an additional data (form field called number_to_create) which tells the method how many of the microposts to create. I just added a new form field like this, in addition to the other micropost form field params:
<%= text_field_tag :number_to_create %>
My question is how do I modify the create method code such that it creates N number of micropost objects vs. just one. So if I pass in 3 from the form along with the other micropost attributes, the method creates 3 identical micropost objects, not just one as it currently does.
Thanks in advance for your help on this.
You could use the param as times
#microposts = Micropost.transaction do
[].tap do |microposts|
param[:number_to_create].times do
microposts << Micropost.create(micropost_params)
end
end
end
respond_to do |format|
if #microposts.all? &:persisted?
format.html { redirect_to #micropost, notice: 'Micropost was successfully created.' }
format.json { render :show, status: :created, location: #micropost }
else
format.html { render :new }
format.json { render json: #micropost.errors, status: :unprocessable_entity }
end
end
The transaction block is to make sure that either all of them gets saved, or none of them gets saved, this way you can fix your errors and recreate them without worrying of getting any stray saved objects
from the default scaffold generator I have the following create action in my blogs controller:
# POST /blogs
# POST /blogs.json
def create
#blog = Blog.new(params[:blog])
respond_to do |format|
if #blog.save
format.html { redirect_to #blog, notice: 'Blog was successfully created.' }
format.json { render json: #blog, status: :created, location: #blog }
else
format.html { render action: "new" }
format.json { render json: #blog.errors, status: :unprocessable_entity }
end
end
end
When the sent form contains errors, my browser is redirected to /blogs URL but in the page the new action is rendered.
This is really ugly in my opinion and (also to simplify my javascript) I would like the browser to remain in the same blogs/new URL.
I tried with changing redirect_to :new instead of render action: "new", but this of course loses the #blog data.
any clue on how to do this?
thanks,
If you want to keep new in your path you could redirect with params like so:
redirect_to new_blog_path(blog: params[:blog])
and then check for these params in blog#new
Here is the premise:
I have a model called Rules, which has a corresponding controller and view.
I'd like the user to be able to create a new rule from their Dashboard, which has a separate view and controller.
The dashboard has three tabs called "Rules", "Rulesets, and "Games." Each tab has its own partial, so for Rules I'm using the _rules.erb partial which looks like this
<div id="dashboard-rules" class="dashboard-panel ui-nav-panel">
<%= button_to'Create A Rule', '#', id: "create-rule-btn", class: "btn btn-primary" %>
<div id="create-rule-form-container">
</div>
...
</div>
Using jQuery, I'm loading the contents of the New Rules page which is controlled by the Rules controller, like this...
$('#create-rule-btn').click (e) ->
e.preventDefault()
$('#create-rule-form-container').load('/rules/new.html .form-horizontal')
This loads just the form from rules/new.html. My problem is that when I click the "Save Rule" button, it redirects to the /rules URL. And then either displays errors or says "Rule Saved Successfully." I'd like for it not to redirect and have the errors show in the dashboard...again, not redirect to /rules URL.
This is my Rules create action, which I think needs to be modified, I'm just not sure how:
def create
#rule = Rule.new(params[:rule])
respond_to do |format|
if #rule.save
format.html { redirect_to #rule, notice: 'Rule was successfully created.' }
format.json { render json: #rule, status: :created, location: #rule }
else
format.html { redirect_to :controler => "dashboard"}
format.json { render json: #rule.errors, status: :unprocessable_entity }
end
end
end
I know I have to fiddle with how respond_to is working, I just don't know how.
Remember that you need to set all variable you set in your dashboard in the create action in order for the following to work. This is because you're rendering the same template as the dashboard so you need to set the variables again.
if #rule.save
format.html { redirect_to dashboard_path, notice: 'Rule was successfully created.' }
format.json { render json: #rule, status: :created, location: #rule }
else
# initialize the variables needed on the dashboard here
format.html { render template: 'dashboard/index' }
format.json { render json: #rule.errors, status: :unprocessable_entity }
end
One more solution is to submit the form via ajax and just refresh the page when the rule is saved.
UPDATE: quick js solution
in the form that creates the rules, add the following
form_for #rule, html: { remote: true } do |f|
This will submit the form via ajax. In your controller, add a format.js line after each format.json
format.json { ... }
format.js
then create a app/views/rules/create.js.erb (or haml) file. In the file, you can add any js you want so add the following
<% if #rule.errors.any? %>
# add js here to append the errors in the page
<% else %>
window.location.reload
<% end %>
I am using almost the code from the regular scaffold. The only change is the 4.times block where I make 4 answer objects on the question. The reason is that I have the corresponding input fields in the view. Now, if the validation fails it renders the new.html.erb again, however after what I have been reading it does not invoke the "new" action again. However I am depending on the 4.times block because otherwise the loop in the view have no answers to loop through. How do I fix this? I tried redirecting but then the error messages disappered.
New action
def new
#question = Question.new
4.times do
#question.answers.build
end
respond_to do |format|
format.html # new.html.erb
format.json { render json: #question }
end
end
Create action
def create
#question = Question.new(params[:question])
respond_to do |format|
if #question.save
format.html { redirect_to #question, notice: 'Question was successfully created.' }
format.json { render json: #question, status: :created, location: #question }
else
format.html { render action: "new" }
format.json { render json: #question.errors, status: :unprocessable_entity }
end
end
end
Exactly as your title suggests: render does just render (the template belonging to) the action and not perform the action itself.
To get your prebuilt answers rendered again in a failed create call, I suggest removing the :reject_if condition from the nested attributes setup. This way, empty submitted answers are preserved. To prevent them from being written to the database, just add regular validations to the Question model...
What you need to look at is the #question in your create action. In theory it should contain the 4 newly built answers so redisplaying the form would also contain these.
If they are not written you may have to look at the accepts_nested_attributes_for to make sure it gets deserialized correctly from the request.
What's the difference between respond_to and respond_with ?
What do they do?
Can anyone post example with the screenshot of output?
Thanks.
There is a pretty complete answer here. Essentially respond_with does the same thing as respond_to but makes your code a bit cleaner. It is only available in rails 3 I think
Both respond_to and respond_with does the same work, but respond_with tends to make code a bit simple,
Here in this example,
def create
#task = Task.new(task_params)
respond_to do |format|
if #task.save
format.html { redirect_to #task, notice: 'Task was successfully created.' }
format.json { render :show, status: :created, location: #task }
else
format.html { render :new }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
The same code using respond_with ,
def create
#task = Task.new(task_params)
flash[:notice] = "Task was successfully created." if #task.save
respond_with(#task)
end
also you need to mention the formats in your controller as:
respond_to :html,:json,:xml
When we pass #taskto respond_with, it will actually check if the object is valid? first. If the object is not valid, then it will call render :new when in a create or render :edit when in an update.
If the object is valid, it will automatically redirect to the show action for that object.
Maybe you would rather redirect to the index after successful creation. You can override the redirect by adding the :location option to respond_with:
def create
#task = Task.new(task_params)
flash[:notice] = #task.save ? "Your task was created." : "Task failed to save."
respond_with #task, location: task_path
end
For more information visit this Blog