Rails 3.2 ActiveRecord SQL syntax error - sql

I just wrote controller for ajax call like this:
def create
#like = Like.new(params[:like])
post = params[:like][:post_id]
uid = params[:like][:ip_address]
#extant = Like.find(:last, :conditions => ["post_id ? AND ip_address = ?", post, uid])
last_like_time = #extant.created_at unless #extant.blank?
curr_time = Time.now
if ((#extant && curr_time - last_like_time >= 24.hours) || #extant.blank?)
respond_to do |format|
if #like.save
format.js
format.html { redirect_to :back }
else
format.html { redirect_to posts_path }
format.json { render :json => #like.errors, :status => #unprocessable_entity }
end
end
else
render :js => "alert('You already liked this.');"
end
end
And this is view erb.
<%= form_for(#like, :remote => true) do |f| %>
<%= f.hidden_field "post_id", :value => #post.id %>
<%= f.hidden_field "ip_address", :value => request.remote_ip %>
<%= submit_tag "Like" %>
<% end %>
And it executes SQL command like this:
SELECT "likes".* FROM "likes" WHERE (post_id '1' AND ip_address = '127.0.0.1') ORDER BY "likes"."id" DESC LIMIT 1
It causes SQL syntax error. I think my ruby syntax is wrong, so how can I fix?

Change your ruby code from this:
"post_id ? AND ip_address = ?"
to
"post_id = ? AND ip_address = ?"

Related

Do I need to reload the comment object or the partial that contains the comment in case of using Ajax in Rails 3?

I have been trying to figure out adding comments without reloading the page using Ajax, after reading few different tutorials this is what I came up to so far, and it's not working:
inside user_comments/_comments.html.erb
<div id="comment_form">
<%= simple_form_for [#commentable, #comment], :html => { :multipart => true }, :remote => true do |f| %>
<div class="picture"><%= image_tag current_user.avatar.url(:thumb) %></div>
<%= f.input :content, label: false, :placeholder => "Add Comment", :input_html => { :rows => 4 } %>
<%= f.submit "Add Comment" %>
<% end %>
</div>
Inside the controller:
def create
#users = User.all
#comment = #commentable.user_comments.new(params[:user_comment])
#comment.user_id = current_user[:id]
##commentable.user_comments.create(:user_id => current_user[:id])
if #comment.save
flash[:notice] = "Successfully created comment."
respond_to do |format|
format.html { redirect_to #commentable }
format.js
#format.js #{ render 'create.js.erb' }
end
else
render :new
end
end
and inside the create.js.erb
// Display a Javascript alert
<% if remotipart_submitted? %>
$("#comments_list").append("<%= escape_javascript(render(:partial => 'user_comments/comments')) %>");
<% end %>
I'm using a Gem called: remotipart
I don't know what I'm missing in the process.
in the console I get:
POST http://localhost:3000/assignments/2/user_comments
200 OK
134ms
which means the post goes through, but the comment doesnt get added back to the partial.
Ok after 2 days! I fixed it, here is what I can share and might help:
1- make sure to include the :remote => true to the form that is about to be submitted
2- Check the controller and see what the Create action is being redirected, in my case I changed to this:
def create
#users = User.all
#comment = #commentable.user_comments.new(params[:user_comment])
#comment.user_id = current_user[:id]
##commentable.user_comments.create(:user_id => current_user[:id])
if #comment.save
flash[:notice] = "Successfully created comment."
respond_to do |format|
format.html
format.js {#comments = #commentable.user_comments}
end
else
render :new
end
end
Then make sure the create.js.erb is written properly:
$("#comments_list").empty()
$("#comments_list").append("<%= escape_javascript(render(:partial => 'comments')) %>");
there you go! I hope some creates a proper tutorial for newbies like me :)!

Syntax error, but correct syntax? unexpected ':', expecting ')'

I have a nested form (see below)
Model Artist (artist is a user)
has_many :art_works
has_many :canvases
accepts_nested_attributes_for :art_works //artworks is what im currently working on
accepts_nested_attributes_for :canvases
Controller art_works
def new
#artist = Artist.find(params[:artist_id])
#artwork = #artist.art_works.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: #artwork }
end
end
def create
#artwork = ArtWork.new(params[:artwork])
respond_to do |format|
if #artwork.save
format.html { redirect_to #artwork, notice: 'artwork was successfully created.' }
format.json { render json: #artwork, status: :created, location: #artwork }
else
format.html { render action: "new" }
format.json { render json: #artwork.errors, status: :unprocessable_entity }
end
end
end
artworks views _form
<%= form_for(#artwork, :url => artist_art_works_path(current_artist) :multipart => true) do |f| %>
<p>
<%= f.file_field :art %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
I was pretty positive that this would work, but i'm assuming my :url is incorrect? I'm not really sure what else it would be though. below are my routes for artworks the reason why I am nesting these things is because an artist can upload art into an artwork model the idea is to have several pieces of art in one artwork (like an album has many images inside of it)
artist_art_works GET /artists/:artist_id/art_works(.:format) art_works#index
POST /artists/:artist_id/art_works(.:format) art_works#create
new_artist_art_work GET /artists/:artist_id/art_works/new(.:format) art_works#new
edit_artist_art_work GET /artists/:artist_id/art_works/:id/edit(.:format) art_works#edit
artist_art_work GET /artists/:artist_id/art_works/:id(.:format) art_works#show
PUT /artists/:artist_id/art_works/:id(.:format) art_works#update
DELETE /artists/:artist_id/art_works/:id(.:format) art_works#destroy
Thank you very much in advance for your help. (sorry for the noobness)
You're missing a comma. Yeah the error message isn't that helpful.
#artwork, :url => artist_art_works_path(current_artist) :multipart => true
vs
#artwork, :url => artist_art_works_path(current_artist), :multipart => true

Routes error on nested controller when submitting form, databasedotcom-gem

I am using the databasedotcom & databasedotcom-rails gem so that I get generate leads into Salesforce from form submissions. It was working standalone until I nested the controller under a parent, and now when I press submit I get this routes error:
No route matches [POST] "/events/516ee9a0421aa9c44e000001/leads/new"
Here is all my code:
resources :events do
resources :leads
end
class LeadsController < ApplicationController
include Databasedotcom::Rails::Controller
def new
#lead = Lead.new
respond_to do |format|
format.html # new.html.erb
format.json { render :json => #lead }
end
end
def create
#lead = Lead.new(params[:lead])
#lead.event_id = params[:event_id]
#lead['OwnerId'] = '005b0000000WxqE'
#lead['IsConverted'] = false
#lead['IsUnreadByOwner'] = false
respond_to do |format|
if #event_lead.save
format.html { redirect_to #lead, :notice => 'Lead was successfully created.' }
format.json { render :json => #lead, :status => :created, :location => #lead }
else
format.html { render :action => "new" }
format.json { render :json => #lead.errors, :status => :unprocessable_entity }
end
end
end
end
<%= simple_form_for [#event, #lead], url: new_event_lead_path do |f| %>
<%= f.input :Download_Brochure__c, :check => "true", :as => :boolean, :as => :hidden %>
<%= f.input :FirstName %>
<%= f.input :LastName %>
<%= f.input :Company %>
<p>Also interested in:</p>
<%= f.input :Sponsor_Request__c, :as => :boolean, :label => "Sponsoring" %>
<%= f.input :Presenting__c, :as => :boolean, :label => "Presenting" %>
<%= f.input :Newsletter_Signup__c, :as => :boolean, :label => "Newletter" %>
<%= f.input :Privacy_Policy__c, :as => :boolean, :checked => true, :label => "Would you like to stay updated" %>
<%= f.button :submit, :label => "Submit" %>
<% end %>
The problem is in your form. With the routes as you have written them, the new_event_lead_path maps to a GET request to your LeadsController#new action. Run rake routes on the command line to confirm this.
You want to submit the form to LeadsController#create. Rails will set this up for you when you use a new instance of Lead in the expression simple_form_for [#event, #lead] provided you don't override the url. Therefore, update your form:
<%= simple_form_for [#event, #lead] do |f| %>

The error occurred while evaluating nil.sort_by

In my articles_controller I have the follow definition
def index
#tags = Article.tag_counts_on(:keywords) || ''
klass = Article
klass = klass.tagged_with(#keyword) if (#keyword = params[:keyword]).present?
#articles = klass.paginate(:page => params[:page])
#articles = Article.where(:state => '4').paginate(:page => params[:page], :per_page => 10)
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #articles }
end
end
and in my views/articles/index.html.erb I have the code:
<% #tags.sort_by(&:count).reverse.each do |k| %>
<% url_opts = {:action => "index", :controller => "articles"}
link_name = "#{k.name} (#{k.count})" %>
<% if #keyword == k.name %>
<%= link_to link_name, url_opts.merge(:keyword => nil), :class => "tag current_tag", :title => "Click again to see all" %>
<% else %>
<%= link_to link_name, url_opts.merge(:keyword => k.name), :class => "tag", :title => "Click to filter by #{k.name}" %>
<% end %>
<% end %>
I use Ruby 1.9.2, Rails 3.0.11 and in Gemfile the gem act-as-taggable-on and the follow code
rails generate acts_as_taggable_on:migration
create tables tags and taggings
In my logs I have this error:
Rendered articles/index.html.erb within layouts/application (57.4ms)
Completed 500 Internal Server Error in 189ms
ActionView::Template::Error (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.sort_by)
The variable #tags is an Array? and have a nil object?
This error is a common Rails (probably Ruby, actually) confuser that just means #tags was nil when you called the sort_by method ... and I guess the error is trying to be helpful since sort_by is a method of Array.
So, why is #tags nil? Fire up rails console (in your project directory) and execute Article.tag_counts_on('something') -- where 'something' is a keyword.
Perhaps you meant in the first line to get keywords from the params array?
#tags = Article.tag_counts_on(params[:keywords])
Also, you need to handle the case where no tags are found, right?
Finaly the solution for this error for me was: NOT DRY. When add the code from
def index to
def all on articles_controller my problem disapear.
my new articles_controller
def index
#tags = Article.tag_counts_on(:keywords)
klass = Article
klass = klass.tagged_with(#keyword) if (#keyword = params[:keyword]).present?
#articles = klass.where(:state => '4').paginate(:page => params[:page])
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #articles }
end
end
def all
#tags = Article.tag_counts_on(:keywords)
klass = Article
klass = klass.tagged_with(#keyword) if (#keyword = params[:keyword]).present?
#articles = klass.where(:state => ['3', '4']).search(params[:search]).order('accepted desc').paginate(:page => params[:page], :per_page => 10)
respond_to do |format|
format.html { render 'index' }
format.xml { render :xml => #articles }
end
end

Create and edit multiple records of the same model

I'm quite new to Rails and to this Q&A website! So hello everyone, I'm a French Rails tester. I have cross posted this question to Railsforum too, to have a better chance on getting an answer :) (http://railsforum.com/viewtopic.php?id=44238)
I need help on something. It seems simple, but in my opinion, not well documented (I browsed the web for 3 days without finding a clean answer. Some partial solutions here, but not a complete and clean one for a newbie!)
I want to add some actions to a default scaffolded controller to handle creation and modification of multiple records in the same form.
rails generate scaffold Item title:string
This is the sample scaffolded code:
app/controllers/items_controller.rb
class ItemsController < ApplicationController
# GET /items
# GET /items.xml
def index
#items = Item.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #items }
end
end
# GET /items/1
# GET /items/1.xml
def show
#item = Item.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #item }
end
end
# GET /items/new
# GET /items/new.xml
def new
#item = Item.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #item }
end
end
# GET /items/1/edit
def edit
#item = Item.find(params[:id])
end
# POST /items
# POST /items.xml
def create
#item = Item.new(params[:item])
respond_to do |format|
if #item.save
format.html { redirect_to(#item, :notice => 'Item was successfully created.') }
format.xml { render :xml => #item, :status => :created, :location => #item }
else
format.html { render :action => "new" }
format.xml { render :xml => #item.errors, :status => :unprocessable_entity }
end
end
end
# PUT /items/1
# PUT /items/1.xml
def update
#item = Item.find(params[:id])
respond_to do |format|
if #item.update_attributes(params[:item])
format.html { redirect_to(#item, :notice => 'Item was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #item.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /items/1
# DELETE /items/1.xml
def destroy
#item = Item.find(params[:id])
#item.destroy
respond_to do |format|
format.html { redirect_to(items_url) }
format.xml { head :ok }
end
end
end
app/views/items/new.html.erb
<h1>New item</h1>
<%= render 'form' %>
<%= link_to 'Back', items_path %>
app/views/items/edit.html.erb
<h1>Editing item</h1>
<%= render 'form' %>
<%= link_to 'Show', #item %> |
<%= link_to 'Back', items_path %>
app/views/items/_form.html.erb
<%= form_for(#item) do |f| %>
<% if #item.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#item.errors.count, "error") %> prohibited this item from being saved:</h2>
<ul>
<% #item.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
In my opinion, I need to add 4 methods to my Item controller:
new_multiple : to initialize the new
multiple form view
create_multiple :
to handle results from the new
multiple form view
edit_mulitple : to
initialize the edit multiple form
view
update_mulitple : to handle
results from the edit multiple form
view
Then, I need to create 2 new views:
new_multiple.html.erb with code for a multiple record (5 in the same time) creation form
edit_mulitple.html.erb with code for a multiple record (5 in the same time) edition form
and maybe _partials to avoid DRY stuff...
Anyone want to help me write these 4 actions and 2 views? I would really appreciate that.
Thanks! :)
Note : In my application items are children of parentItems but I DON'T WANT to use nested_form to create items in parentItems forms like in railscast 196 and 197.