Rails' .save
and .update
return true/false
(boolean) depending on whether the action was successful.
The standard way of utilizing that in your flow is as follows:
def update
@node = Node.find params[:id]
respond_to do |format|
if @node.update(node_params)
format.js #-> invokes /views/nodes/update.js.erb
format.json { render json: @node.to_json }
format.html
else
format.js #-> invokes /views/nodes/update.js.erb
format.json
format.html
end
end
end
You shouldn't be using the @video.update
using the exact same data as @node
- you can do that in the model. You'll be best using associations etc, which I can explain if required.
#app/models/node.rb
class Node < ActiveRecord::Base
belongs_to :media #?
before_save :set_media, on: :update
private
def set_media
self.media.name = self.name
self.media.description = self.description
end
end
Ajax
My front-end UI developer has some jQuery that I need a callback for
Since I don't know the spec for this, I cannot give you any specific code.
What I can tell you is that if you're using ajax, you have to make sure you understand the difference between server-side & client-side code.
I don't want to insult your intelligence but I'll explain it for posterity's sake...
Frontend ajax will look like this:
#app/assets/javascripts/application.js
$(document).on("click", ".element", function(){
$.ajax({
url: "...",
data: ....,
success: function(data) { },
error: function(response) {}
});
});
... since this is client side code, you can only deal with data returned from the server. A common misunderstanding is many people thinking they'll somehow be able to use Ruby code/methods in this. No.
You can only send back pre-packaged data to this, so if you wanted your data to be condition, you'd do something like this:
def update
@node = Node.find params[:id]
@returned = "yes" if @node.update(node_params)
render [x], layout: !request.xhr?
end
This will allow you to send back conditional data, with which you'll be able to use the front-end JS to manipulate:
$.ajax({
...
success: function(data) {
... do something with data
}
--
If you wanted to use server side code, you'll be better using the inbuilt format.js
functionality:
def update
@node = Node.find params[:id]
respond_to do |format|
format.js #-> app/views/nodes/update.js.erb
end
end
This does allow you to use Ruby code, as the JS is rendered server-side, and passed to the browser. I'm not sure as to the specifics, but I know you can do the following with it:
#app/views/nodes/update.js.erb
<% if @node.something %>
$("js")....
<% else %>
...
<% end %>