accessing POST parameters - ruby-on-rails

When I add a new "product" using my scaffold create rails app, the following line properly adds a new product
#product = Product.new(params[:product])
When I try to add a new product using the following URL (trying to POST data up from a java program).
http://localhost:3000/products?serial=555&value=111
The product is not created, however I can access the "serial" and "value" values like this:
#product = Product.new
#product.serial=params[:serial]
#product.value=params[:value]
#product.save
To further confuse me, if I use the rails app to add a new product, the params[:serial] and params[:value] variables are empty.
Can someone please point me in the right direction.
Thanks

The Model.new method takes a hash.
params[:product] actually contains something like {:serial => 555, :value => 111}
The url you would want to use is:
http://localhost:3000/products?product[serial]=555&product[value]=111
(Make sure that you are indeed using POST)
If you want to keep your current url scheme you would have to use:
#product = Product.new({:serial => params[:serial], :value => params[:value]})
You can also determine exactly what is available inside of params by printing it out to console using:
p params
Good luck!

Related

Affecting resulting params set from form_for

Relative newbie here to Ruby on Rails.
Using the standard form_for method in the view for my SomeobjController#new action
= form_for #someobj do |f|
.
.
.
%p.submits
= f.submit "Submit", :class => "submit"
a submission param[] array is produced that contains a hash of #someobj for all the fields set in the form, such that
param[someobj] => { "field1" => "val1", "field2" => "val2", ... }
I would prefer to put a different value, the result of someobj.to_s to param[someobj] for the SomeobjController#create to work with, such that
param[someobj] => "strvalfromtos"
I doubt it's relative, but just in case, the model underlying this #new action is not persistent in the database (i.e., Someobj is not derived from ActiveRecord::Base, though some portions of ActiveModel are included.)
I haven't had luck trying to adjust this until after #create is invoked, but its the submission from #new to #create that I want to amend. It's not clear to me if I should be focusing more on the form_for statement or doing something special in the controller (I'm guessing the form_for is the right focus).
And, yes, this whole thing is probably a bit OCD of me, but the actual fieldnames are long (appropriately for the model) but data needed by #create is very small.
Is there a relatively painless way to do this, assuming that someobj.to_s has already been written?
Many thanks,
Richard
Change
When you submit the form, your controller will receive the params hash, as you've stated (Rails params explained?)
That means you can change any value in the hash that you wish:
def create
#has access to the params hash
params[:owner][:key] = value
end
As the create method receives the hash object, you'll have to change it in here. But because it's a standard hash (which has already been declared), you should be able to alter it as required
Add
If you want to add values to the params hash, you can use the .merge method, like this:
def create
#has access to the params hash
params[:key].merge(user_id: current_user.id)
end

Rails Rating System with strange helper method

there's an issue, that is bothering me.
I'm following this "Ruby on Rails"-Tutorial to implement an ajaxified rating system
http://eighty-b.tumblr.com/post/1569674815/creating-an-ajaxified-star-rating-system-in-rails-3
Die author uses a self written helper method called "rating_ballot" which seems pretty redundant to me, because it checks if a rating has been given yet and otherwise forms a new one with
current_user.ratings.new
But that actually is being done more or less in the ratingscontroller
using this helper method the form looks like this
= form_for(rating_ballot, :html => { :class => 'rating_ballot' }) do |f|
But any other form (for example posting reviews) uses the instance variable instead of a helper method.
I want the form_for tag to look like this
= form_for(#rating, :html => { :class => 'rating_ballot' }) do |f|
but this only works for updating ratings, not creating new ones.
why is this "rating_ballot" so important ?
Take a look on that part
def rating_ballot
if #rating = current_user.ratings.find_by_photo_id(params[:id])
#rating
else
current_user.ratings.new
end
end
It try to find out #rating if exists and create new instance if not exsits
you can do it in you controller for example:
#rating = current_user.ratings.find_by_photo_id(params[:id])
#rating ||= current_user.ratings.new # create instance if did not find existing once
ans then use it in form like you wrote
I'm guessing the value of #rating is nil, which is why using this form for the #create action isn't working. The first argument should be a new object, or an object that represents an existing record, in order to create or update, respectively.
Another alternative way of using the form_for method is to supply a symbol representing the name of the class and also specifying the :url argument according to how your routes are specified. This is only good for creating though since the symbol doesn't represent an existing record.

passing id parameter from show action to new action via link_to, rails

I have some show action that displays one category. But from there I want via link to create new product. Point is that I passed category id and name via link_to.
It goes well, it opens Product/new action. And in browsing bar there is link like this http://mysite/products/new?id=43&name=Skeleji .its okay.
But how can I make those id and name available in form, where I am filling information about new product?
After this when I click create, I want that theese values such category_id saves in db along with other information abaut product.
Between, Product and Category I have built relationship.
So far my code looks like this .
My Category/show action code looks like this.
<%= link_to "Add Product", {:controller => "products", :action => "new", :id => #category.id, :name => #category.name }%>
Product controller, new action looks like this.
def new
#product = Product.new
#product.category_id = #category.id
end
Clicking create it creates project, but without category_id. Where could be the problem ?
Maybe the code what is under new action,actually should be under create action. About year ago I managed to do such thing, but I can't find that project.:(
You should be able to just set the values in your new action:
def new
#product = Product.new
#product.category_id = params[:id]
#product.name = params[:name]
end
Then they will appear as such in your form.
But I don't think it's a good idea to call your parameter id because it's a default parameter name for resourceful routing. params[:id] in the ProductsController should typically always refer to a Product object. As it happens, you're using it in the new action which in normal use will never receive an id parameter so I doubt you'll get in any trouble, but it isn't very semantic.
If you let Product accept nested attributes for Category then I think you'd be able to simply do:
#product = Product.new(params[:product])
if you structured your params like: :product => { :name => "whatever", :category_attributes => { :id => 1 } } but that might be overkill depending on your needs.
Have you tried #product.category_id = params[:id]
Usually anything the ? in the url is contained with the params variable.

Trouble Accessing Ruby Params on RhoMobile

I'm new to Ruby so please excuse my ignorance. I really didn't know how to word this question so this may also be part of the reason I haven't found an answer online.
I'm working with Rho Elements, and I'm trying to pass something from one page to another. I've made some good headway but run into something that I do not understand. I can pass through an ID like so
<input type="hidden" name="id" value="<%= #orderdetails.object %>"/>
I then grab the ID(only doing this right now to make sure I do get the ID)
#id = #params['id']
then redirect to another page
redirect url_for(:action => :newpage, :id => #id).
This is where my problems start. When I debug the application I get past the redirect and enter :newpage
def newpage
#orderdetails = OrderDetails.find(#params['id'])
if #orderdetails
render :action => :newpage, :back => url_for(:action => :index)
else
redirect :action => :index
end
end
Once here I check
#params['id]
and this is what is displayed.
#params {"id"=>"{131113212443313.17}"}
"id" ""
#params {"id"=>"{131113212443313.17}"} is shown by eclipse and when I break into the variable "id" "" is shown.
Why can I see the ID that I want to use to grab the orderdetails that was just created but also have the actual variable be empty?
**EDIT: This is the information I'm trying to pass.
#params {"id"=>"131113212443313.17", "next"=>"asleftnext", "orderdetails"=>
{"AsFoundMeterRead"=>"", "AsFoundImage"=>""}}
"id" "131113212443313.17"
"next" "asleftnext"
"orderdetails" {"AsFoundMeterRead"=>"","AsFoundImage"=>""}
Use params in the controller, not #params. Also the canonical form of accessing keys is params[:id].
Like its say in the previous answer you access the params in the controller in this way
#id = params[:id]
Also if you are using Rails 3 or higher you may want to use the new url way is less verbose so its more easy to read.
newpage_controllername_url(:id => #id)
you can also ask for the path with this method.
If you don't know if you are passing right the params you can display the content using
params.inspect
You can view the content of any object with inspect

Passing a model attribute to a Rails view using redirect_to

I'm trying to pass a model attribute to a view, after successfully setting it to a new value from inside an action in my controller. But this variable is always nil by the time it gets to the view, so I can't use it to conditionally display stuff. I should add that this attribute is not a field in the database. What am I missing/doing wrong?
Here is the code in my model:
attr_accessor :mode
#getter
def mode
#mode
end
#setter
def mode=(val)
#mode = val
end
...in the controller:
#report.mode = "t"
redirect_to edit_report_path(#report)
...and in my view:
<%= build_report(#report.mode) %>
...but this helper method never gets the variable I just set in the controller. It is nil. What gives? Clearly I'm missing something basic here because this seems like it should be straightforward. Any insight would be greatly appreciated.
Thanks.
edit_report_path generates a URL with the ID of #report in it.
redirect_to essentially creates a whole new request, and goes to that URL. When it gets to edit, all it has is the ID. Usually that's fine - it looks up the object and keeps going, but of course it's not going to have the non-db field you set.
There are a couple ways to fix this. You can use :render instead to get to the edit page - then #report will have the field set.
#report.mode = "t"
render :action => edit and return
Or, you can make mode a database field.
The problem here is in the redirect_to. When you redirect somewhere else all instance variables are lost. So when you set #report.mode = "t" it sets the attribute. But when you redirect that data is lost.
I am assuming the <%= build_report(#report.mode) %> is in edit_report.html.erb and the code from when you set 'mode' is not in the edit action. If this is the case you may be able to pass the report.mode to the edit action in the url like so:
build_report(#report.mode, :mode => "t")
The problem is the redirect_to; you're returning a response to the client that causes it to redo the request with a different url. In that second request the mode isn't set because you didn't save it before wrapping up the first request.

Resources