Error: wrong number of arguments (1 for 0) => if no debug or .to_yaml used - ruby-on-rails-3

I get an error with the following code, but with a logger row or debug is the output correct. It's a little bit strange for me. (Rails 3.1.0 and 3.0.9 and Ruby 1.8.7)
Controller contains:
def index
#privatmessages = Privatmessage.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => #privatmessages }
end
end
index.htm.erb
<% #privatmessages.each do |privatmessage| %>
<%= privatmessage.id %>
<% end %>
That code produce the error:
ArgumentError in Privatmessages#index
Showing ../app/views/privatmessages/index.html.erb where line #2 raised:
wrong number of arguments (1 for 0)
But the output is correct and without errors, if I add the following line at the controller:
logger.info "Messages: {##privatmessages.to_yaml}"
or if I add inside of the each loop at the index.html.erb the line:
<%= debug privatmessage %>
Has anyone an advice for me?

Issue found and solved!
The problem was that I used "send" as a column name in the table, but "send" is a reserved method for Rails core. After renaming the column in the table to "sendout" it works.

Related

Create New Rails Record without HTML Redirect

I have a Rails app where I have Article and Like models. I want someone to be able to create a Like record, similar to Facebook, where the database records the new record without redirecting them. The two requirements I have are: create a new Like record without redirecting the user and have a flash or js message that confirms the record was created.
I tried putting this in my view. However, when I do this, it creates two identical records:
<%= form_for #like, :remote=> true do |f| %>
<%= f.hidden_field(:article_id, :value => article.id) %>
<%= f.submit "Like" %>
<% end %>
I also, tried this which resulted in one record creating, but it took me to localhost:3000/likes:
<%= form_for #like do |f| %>
<%= f.hidden_field(:article_id, :value => article.id) %>
<%= f.submit "Like" %>
<% end %>
and then in the Like Controller commenting out the format.html and json:
def create
#like = Like.new(params[:like])
respond_to do |format|
if #like.save
# format.html { redirect_to #like, notice: 'Like was successfully created.' }
# format.json { render json: #like, status: :created, location: #like}
else
format.html { render action: "new" }
format.json { render json: #like.errors, status: :unprocessable_entity }
end
end
end
What's the best way to meet my two requirements? Thank you!
I assume Articles and Likes are related. When you want to 'like' an article you are actually updating that article, right? In other words, you would have to change the redirect within the update action of the articles controller.
P.S. I would use some javascript for submitting a form, for example:
<script type="text/javascript">
$(document).ready(function() {
$('.edit_[here_comes_the_name] input[type=checkbox]').click(function() {
$(this).parent('form').submit();
});
});
</script>
This example submits the input from a particular form (the parent) when clicking on the check_box. Of course you would have to adjust it to fit your needs.

No route matches :action => edit rails 3

I don’t understand why I am getting the above error message when trying to update a recipe
This is my output of rake routes
recipes GET /recipes(.:format) recipes#index
POST /recipes(.:format) recipes#create
new_recipe GET /recipes/new(.:format) recipes#new
edit_recipe GET /recipes/:id/edit(.:format) recipes#edit
recipe GET /recipes/:id(.:format) recipes#show
PUT /recipes/:id(.:format) recipes#update
DELETE /recipes/:id(.:format) recipes#destroy
root / public_pages#index
My controller looks like this
def edit
#recipe = Recipe.find(params[:id])
end
def update
#recipe = Recipe.find(params[:id])
if #recipe.update_attributes(params[:recipe])
redirect_to recipes_path, :notice => "Successfully updated recipe"
else
render :action => 'edit'
end
end
And my link to edit the post
<%= link_to "Edit Recipe", edit_recipe_path(#recipe) %>
the full error is (this is when trying to access the recipes page
Routing Error
No route matches {:action=>"edit", :controller=>"recipes"}
Try running rake routes for more information on available routes.
and finally the form i am using, now the only thing I can think of is that there is an issue with my form, though i thought that you could use the same form for new and edit? though i could be totally wrong
Anyone have any ideas
ok so it seems as if i needed this in my view
<%= link_to "Edit Recipe", edit_recipe_path(r.id) %>
this was because i was passing
<% #recipes.each do |r| %>

Rails undefined method `map' for nil:NilClass

I'm trying to create a select field for a form that selects based on records selected for a model (called "Cancellation_Reasons").
In my model called Cancellation:
<%= form_for(#cancellation do |f| %>
<%= options_from_collection_for_select(#cancellation_reasons, :id, :name) %>
<% end %>
In the Cancellation_Controller:
def new
#cancellation = Cancellation.new
#cancellation_reasons = CancellationReason.find(1)
respond_to do |format|
format.html # new.html.erb
format.json { render json: #trade }
end
end
When I run CancellationReason.find(1) in the the Rails Console it finds the record, so #cancellation_reasons isn't nil. I think that it's probably in how I'm using the select helpers (I've tried experimenting with them, but I'm not quite sure which one to use even after reading the Rails Guide and Rails API docs).
options_from_collection_for_select expect a collection (even it it is a collection of 1).
So change the code to be:
def new
#cancellation = Cancellation.new
#cancellation_reasons = CancellationReason.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: #trade }
end
end

Format.js will only render a partial that contains a single line

Rails 3.2.1: I have the following div that calls a partial
<div id="weighin">
<%= render :partial => "my_weight/weighin" %>
</div>
The partial contains a form that posts ajax (ie has :remote => true) to a controller with:
respond_to do |format|
format.js
end
The .js.erb file has a single line:
$("#weighin").html("<%= render :partial => "my_weight/weighin1" %>");
The _weighin1.html.erb partial file has a single line:
<p><%= #my_weight[1].weight %></p>
This works, in that the original div is replaced with the value of the #my_weight field - so the fundamental structure is all working ok
However, Rails will not handle any more code in the partial - if I add so much as a carriage return to the end of that one line, the server log confirms all ok, but no script gets run on the page - ie nothing changes.
The same happens if I try to put more html in the partial, but put it all in a single line - this doesnt run either.
How can I output more than a single short statement in a partial?
OK, I figured this out:
$("#weighin").html("<%= escape_javascript(render :partial => "my_weight/weighin1") %>");
escape_javascript is essential
What is confusing is that, depending on what is in the html() you are sending, this will sometimes work without escape_javascript, leading one to a false conclusion... :-)

expected Hash (got Array) for param 'samples'

I have been following Railscasts episodes of Nested forms and complex forms. During the time of creating multiple model in a single form I was able to edit, update, delete and create records for sample models that were nested in the Batch model.
I have been breaking my head from a long time and tried searching around as well but could not get any right solution for solving this problem.
my development log file gives me the following error.
ERROR MESSAGE:
Status: 500 Internal Server Error
expected Hash (got Array) for param `samples'
in my controller I have the update action like this
def update
#batch = Batch.find(params[:id])
respond_to do |format|
if #batch.update_attributes(params[:batch])
flash[:notice] = 'Successfully updated Batch.'
format.html { redirect_to(#batch) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #batch.errors, :status => :unprocessable_entity }
end
end
end
my view is something like this:
<%= form_for #batch do |f| %>
......
<%= f.fields_for :samples do |s_form| %>
.... s_form things
<% end %>
<% end %>
my model contains the same stuff :
has_many :samples, :dependent => :destroy
accepts_nested_attributes_for :samples, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
All suggestions are appreciated.
for others who met the same problem:
this error is caused when you have two fields in your form like:
video: 'some string'
video['url']: 'some url'
then rails will crash with the error: expected Hash (got String) for param
the solution is quite simple: change 'video' to something else. e.g.:
video_origin_url: 'some string'
video['url']: 'some url'
I had the same problem, and just fixed it.
Check the headers of your request. I mine I saw:
weight[2][name]:Tests
weight[2][value]:75
weight[1][name]:Quizzes
weight[1][value]:25
weight[][name]:Foo
weight[][value]:
It was the last two which caused the issue. In my case I had to give this weight an ID to get rid of the error.
I also got this error Invalid request parameters: expected Hash (got Array) for param 'cell'.
In my case, I misformed the field name like
f.text_field :name, name: 'cell[name][]'
this was causing the error. Now I did the following and the error is gone:-
f.text_field :name, name: 'cell[][name]'
in this solution I was actually trying to get data in array format.
I had this problem, when the user typed the params himself in the request like:
https://example.com/page?samples[]=1&samples[test]=2
Debugging the code, I got down to a Rack::QueryParser.parse_nested_query method in the rack gem:
# parse_nested_query expands a query string into structural types. Supported
# types are Arrays, Hashes and basic value types. It is possible to supply
# query strings with parameters of conflicting types, in this case a
# ParameterTypeError is raised. Users are encouraged to return a 400 in this
# case.
def parse_nested_query(qs, d = nil)
params = make_params
unless qs.nil? || qs.empty?
(qs || '').split(d ? (COMMON_SEP[d] || /[#{d}] */n) : DEFAULT_SEP).each do |p|
k, v = p.split('=', 2).map! { |s| unescape(s) }
normalize_params(params, k, v, param_depth_limit)
end
end
return params.to_h
rescue ArgumentError => e
raise InvalidParameterError, e.message, e.backtrace
end
From the docstring:
It is possible to supply query strings with parameters of conflicting types, in this case a ParameterTypeError is raised. Users are encouraged to return a 400 in this case.
I found few solutions here Rails ActionController::BadRequest causes 500 Server Error on production server