I want to call a controller function with ajax that works fine, problem is the object generation.
I try it this way:
#tag = Tag.new params[:tagname]
#tag.save
But so I got error 500 back
If I do this
#tag = Tag.new params.permit[:tagname]
#tag.save
That "works" but in database the column tagname is Null ...
whats the problem?
What can I do to fix that?
If I understand what you're doing here correctly, your problem is that you're passing a string to Tag#new. However, unless you've modified the Tag class, you actually need to do something like:
Tag.new name => params[:tagname]
That is, "new" doesn't take a string (again, unless you've modified it) it takes a Hash.
Correct solution is
#tag = Tag.new
#tag.tagname = params[:tagname]
Thaks for the hint with hash problem ;)
You could do this in a single statement using create
Tag.create(tagname: params[:tagname])
Related
My View make a redirect an pass the Params
?cart_item[price]=5%2C70€
.
I try to get this with
#price = [:cart_item][:price]
, but there i get the error "can't convert Symbol into Integer".
I try it with codes like ":cart_item_price" or ":cart_item.price" but always no variable was founded
How can i get this price in my other action ?
You are forgetting something in your code.
What you must do is #price = params[:cart_item][:price] this should work.
Also ensure you check if the key cart_item exists before you assign the value to the price variable.
Something like this should work #price = params[:cart_item][:price] if params[:cart_item]
You have omitted the params hash to extract the value from. Hence the error.
Hope that helps.
I try to get this with
#price = [:cart_item][:price]
I think you need to put an object before this [:cart_item][:price]. Maybe params?
#price = params[:cart_item][:price]
I'm a novice at RoR. Tell me please how to take attributes from ActiveRecord::Relation? For Example I write:
#user = User.where(code: 123)
next I want to take attribute id
id = #user.id
but this method is not working. Thanks in advance
When use .where it gives you an active record relation so you can't find id directly on it because it's a relation not a single model object.
Fix:
You can do
#user = User.where(code: 123).first
OR
You can use dynamic finders
#user = User.find_by_code(123)
If you want to find single user with code == 123, you can use find_by method, like this:
#user = User.find_by(code: 123)
It returns User instance, so you can call id method on it.
EDIT: If you use Rails prior to 4.x version, you can use dynamic find_by_code finder:
#user = User.find_by_code(123)
You are using where clause it returns array. Use it like :
#user = User.where(code: 123).first
Above is not right way for query. So you can also write your code to find user like :
#user = User.find_by_code(123)
With above two ways you get single object and you can find any attribute from it. #user.id etc
I guess you are missing first, where returns an array of objects, so you need to use first to get the object out of array
Do this
#user = User.where(code: 123).first
id = #user.id
I've created a form with about 40 fields available to edit, I'm trying to save them to a database using the controller. I currently have this code:
c = Form.find(params[:id])
if c
params.each do |k,v|
c.k = params[:v]
end
Which doesn't work, I get this error: undefined method 'k='
if I was going to write them all out manually it would look like this:
c = Form.find(params[:id])
if c
c.title = params[:title]
c.reference = params[:reference]
....
etc.
Assuming that you're trying to update the attributes on your Form record based on what gets passed into params, try this as a basic outline:
c = Form.find_by_id(params[:id])
if c
params.each do |k, v|
c[k] = v
end
c.save!
end
Your original code's use of params[:v] was probably not doing what you were intending, and you really meant for it to be params[:k] instead. However there's actually no need to look up the value for that key inside the loop like that because you already have the value at hand in v.
Here's a quick rundown on the ways of interacting with ActiveRecord attributes: http://www.davidverhasselt.com/2011/06/28/5-ways-to-set-attributes-in-activerecord/
i dont know what you are trying todo but your code seems to be very odd. Solution is as follow
c.send "#{k}=", params[:v]
What about
c = Form.find(params[:id])
c.update_attributes(params[:form])
Note that I guessed the [:form] part in the second line, it depends on your form. check your html source, and see if your fields are something like this:
<input name="form[field_name]" ...
As you see, name contains an "array like" form. Check your HTML source and adapt (so if its name="foo[field_name]", you need to use c.update_attributes(params[:foo]))
Given a query like:
current_user.conversations.where("params[:projectid] = ?", projectid).limit(10).find(:all)
params[:projectid] is being sent from jQuery ajax. Sometimes that is an integer and the above works fine. But if the use selects "All Projects, that's a value of '' which rails turns into 0. which yields an invalid query
How with rails do you say search params[:projectid] = ? if defined?
Thanks
I think you may have mistyped the query a bit. "params[:projectid] = ?" shouldn't be a valid query condition under any circumstances.
In any case, you could do some sort of conditional statement:
if params[:project_id].blank?
#conversations = current_user.conversations.limit(10)
else
#conversations = current_user.conversations.where("project_id = ?", params[:project_id]).limit(10)
end
Although, I'd probably prefer something like this:
#conversations = current_user.conversations.limit(10)
#converstaions.where("project_id = ?", params[:project_id]) unless params[:project_id].blank?
Sidenotes:
You don't have to use .find(:all). Rails will automatically execute the query when the resultset is required (such as when you do #conversations.each).
Wherever possible, try to adhere to Rails' snakecasing naming scheme (eg. project_id as opposed to projectid). You'll save yourself and collaborators a lot of headaches in the long run.
Thanks but if the where query has lets say 3 params, project_id, project_status, ... for example, then the unless idea won't work. I'm shocked that Rails doesn't have a better way to handle conditional query params
EDIT: If you have multiple params that could be a part of the query, consider the fact that where takes a hash as its argument. With that, you can easily build a parameter hash dynamically, and pass it to where. Something like this, maybe:
conditions = [:project_id, :project_status, :something_else].inject({}) do |hsh, field|
hsh[field] = params[field] unless params[field].blank?
hsh
end
#conversations = current_user.conversations.where(conditions).limit(10)
In the above case, you'd loop over all fields in the array, and add each one of them to the resulting hash unless it's blank. Then, you pass the hash to the where function, and everything's fine and dandy.
I didn't understand why you put:
where("params[:projectid] = ?", projectid)
if you receive params[:project] from the ajax request, the query string shouldn't be:
where("projectid = ?", params[:projectid])
intead?
And if you are receiving an empty string ('') as the parameter you can always test for:
unless params[:projectid].blank?
I don't think i undestood your question, but i hope this helps.
I currently have 3 tables.
snippet
tags
snippet_tags
I'm using HABTM.
So I did a form to save a snippet with tags. Keywords are in a text field, separated by commas.
What I need to do is to take the string from this text field, loop on the keywords, check if they exist, if not create them, and THEN save the snippet.
I tried with a before_save but it doesn't seem to go by that way..
So if you could help me, it'd great!
Thanks a lot!
I think JosephL's answer is pretty good. Although, I would do it all in the snippets_controller action:
def create
#snippet = Snippet.new(params[:snippet])
#snippet.tags = params[:tags].split(',').collect { |tag| Tag.find_or_create_by_name(tag) }
if #snippet.save
# do something when successful
else
# do something when saving failed
end
end
Sorry for that long, one-line statement. ;-)
I didn't test the code, but I hope it works.
Tag.find_or_create_by_name will do exactly that: when a tag with that name exists, it will return it, otherwise it will create the new tag on the fly and return that.
This way, the tags are already saved, before you call #snippet.save.
Please note, that I just assumed, how your variables and parameters are named.
Here is a version of your create method. The main change is not creating a Snippet_Tag. If your HABTM association is set up correctly then your snippet will have a tags collection which you can add your tags to. The collection will be persisted as Snippet_Tags by ActiveRecord. See the rails associations guide for more details on HABTM associations.
def create
# Creating the snippet
#snippet = Snippet.new
#snippet.title = params[:snippet][:title]
#snippet.content = params[:snippet][:content]
# loop through the tags
params[:snippet][:tags].split(',').collect do |tag_string|
tag_string.strip!
if tag_string.length > 0
# Find or create tag
tag = Tag.find_or_create_by_name(tag_string)
# Add tag to tags collection
#snippet.tags << tag
end
end
if #snippet.save
# do something when successful
else
# do something when saving failed
end
end
Use split to break your string into an array of the tags
Find each tag by name
If not found then create the tag
Add the tag to the snippet
Save the snippet (in your controller)
Example method to put in your snippet model
def add_tags(tag_list_string)
tag_array = tag_list_string.split ','
tag_array.each do |tag_name|
tag = (Tag.find_by_name(tag_name) || Tag.create(:name => tag_name))
self.tags << tag
end
end
Try before_update?