I am trying to Ajaxify a Ruby on Rails application to avoid the reloading of every page after a user interaction.
I now manage to have a new idea created behind the scenes but not to display it once it has been created.
Here is my code :
form in the ideas views :
<div id="new_proposition_form" style="display:none">
<%= form_for(@new_proposition, :remote => true) do |f| %>
<%= f.text_field :title, :class => "proposition_input", :id => "new_proposition_input" %>
<%= f.hidden_field :created_by %>
<%= f.hidden_field :father_id %>
<%= f.hidden_field :procontra %>
<%= f.hidden_field :created_at %>
<% end %>
</div>
create action in the ideas controller :
def create
@idea = Idea.new(params[:idea])
@idea.created_at = Time.now
respond_to do |format|
if @idea.save
format.html { redirect_to play_path, :notice => 'Idea was successfully created.' }
format.json { render :json => @idea, :status => :created, :location => @idea }
format.js
else
format.html { render :action => "new" }
format.json { render :json => @idea.errors, :status => :unprocessable_entity }
end
end
end
create.js.erb in the ideas views :
$("<%= escape_javascript render(:file => 'ideas/new_proposition.html.erb') %>").insertBefore('#end_of_propositions_list');
where "end_of_propositions_list" is the unique identifier of the displayed ideas list.
What I am struggling with is the following :
if the new_proposition.html.erb view in the ideas views is something like :
<div>
New proposition added
</div>
with a code that is not referring to any object or variable it kind of works, i.e. the user can see a confirmation of what happened. Therefore I know that the remote action initiated in the browser hit the controller which hit the javascript template which hit a partial view.
Now I would like the newly created idea to appear instead, using a partial that retrieves its attributes and takes care of the formatting. I feel I need to pass the id of the newly created idea from the create action in the ideas controller to the create.js script that is called by format.js and then to the partial so that it knows what idea to pull from the database.
I do not know how to handle this parameter passing from the create controller action to the create.js and to the partial view and would really appreciate your help.