Couchdb finder using CouchRest - ruby-on-rails

I just want to know how can I build a find_all_by_action_and_author_id method in Rails with while using the couchdb. My Model looks like this:
class Activity < CouchRest::Model::Base
property :action, String
property :author_id, String
end
if I try to build a View like that:
design do
view :by_action_and_author_id
end
I dont know how to get the right result, I tried it with this:
Activity.by_action_and_author_id(:keys => [['action','foo'], ['author_id', '1']]).all
But the result is always a empty hash. What is the best way to do this? Any examples?
With PostgreSQL it would look like this
Activity.where(action: 'foo', author_id: '1').all
it cant be so complicated
Thanx

have a look at the generated couchdb-view! you can see which keys get emitted. there is no thing as a mapping there, so i think that [['action','foo'], ['author_id', '1']] should be just ['foo', '1'].
i do not know for sure how couchrest-models handles views, but you can find more infos here: http://www.couchrest.info/model/view_objects.html
have a look at the tag-example.

Related

How to output all attributes jbuilder, without having to specify them all?

I'm using json to store document versions of my data in postgresql. I would like to output an entire tree of objects with children, children of children etc and all attributes. If any attributes are added to any of the objects at a later date, I would like them to be include in subsequent json.
Is there any way to output the entire contents without having to least each and every attribute? ie not like this:
json.(object_name, :id, :attr1, :attr2.... etc)
I know this is an old thread, but I was wondering the same thing, and ended up here. Then I found a great answer here => How to extract all attributes with Rails Jbuilder?
#uiureo suggests to use json.merge!, and that worked perfactly for me :)
json.merge! object_name.attributes
If you want your json to ouput like this:
{"id":1,"attribute1":1,"attribute2":2}
You can do this:
json.array! #my_object
However, if you want output that looks likes this:
{"my_object":{"id":1,"attribute1":1,"attribute2":2}}
You can do this:
json.my_object #my_object
You may look at json.except!
json.except! #resource, :id, :updated_at
json.except! #resource
https://github.com/chenqingspring/jbuilder-except

Is there a way to skip serialization in Rails 3.1?

In my Rails 3.1 application, I need to read the raw data of a field, without serialization, and then write it down without serialization. Is this possible? How?
By serialization I mean
class Tenant
serialize :profile_template
end
I obviously can access the field like this:
> t.profile_template
=> [{:title=>"Page 1", ....}]
I then also tried with read_attribute_before_type_cast (as per lucapette's suggestion):
> t.read_attribute_before_type_cast(:profile_template)
=> nil
Using a string instead of a symbol had a different but disappointing result:
> t.read_attribute_before_type_cast("profile_template")
=> [{:title=>"Page 1", ...}]
and same with the attribute name:
> t.profile_template_before_type_cast
=> [{:title=>"Page 1", ...}]
Just for the record, what I was expecting is:
"---
- :title: Page 1
...."
In all samples, ... is the rest of a very long structure.
Yes there is a way. You have to use
read_attribute_before_type_cast(:foo)
where :foo is the name of the field. The doc is not that good about that but I remember that there is a good explanation about it in The Rails 3 way.
EDIT
Although you're saying that this way isn't working for you I re-read the piece of information from the above-mentioned book. Well, there's another way of doing that. You can use
bar = foo_before_type_cast
where foo is the name of the field. It works like magic finders, pre-pending the name of the field to _before_type_cast . I can't try it right now but it really should work fine.

How to retrieve all attributes from params without using a nested hash?

I am currently in the process of making my first iphone app with a friend of mine. He is coding the front end while I am doing the back end in Rails. The thing is now that he is trying to send necessary attributes to me with a post request but without the use of a nested hash, which means that that all attributes will be directly put in params and not in a "subhash". So more specifically what I want to do is be able to retrieve all these attributes with perhaps some params method. I know that params by default contains other info which for me is not relevant such as params[:controller] etc.. I have named all attributes the same as the model attributes so I think it should be possible to pass them along easily, at least this was possible in php so I kind of hope that Rails has an easy way to do it as well.
So for example instead of using User.new(params[:user]) in the controller I have the user attributes not in the nested hash params[:user] but in params directly, so how can I get all of them at once? and put them inside User.new()?
I found the solution to my problem. I had missed to add the attr_accessible to my model which was what initially returned the error when I tried to run code like: User.new(params) having been passed multiple attributes with the post request.
The solution was very simple, maybe too simple, but since this is my first real application in Rails I feel that it might be helpful for other newbies with similar problems.
If you would like to just pass a more limited version of params to new, you should be able to do something like the following:
params = { item1: 'value1', item2: 'value2', item3: 'value3' }
params.delete(:item2)
params # will now be {:item1=>"value1", :item3=>"value3"}
Also see this for an explanation of using except that you mention in your comment. An example of except is something like:
params.except(:ssn, :controller, :action, :middle_name)
You can fetch the available attributes from a newly created object with attribute_names method. So in this special example:
u = User.create
u.attributes = params.reject { |key,value| !u.attribute_names.include?(key)
u.save

Sunspot indexing and searching tags returns everything

I am using act_as_taggable_on for tagging in our projects, along with sunspot/solr for searching.
We get a strange unexpected result. First our setup (short version):
Model:
Class Person
has_many :projects
searchable do
string :project_tags, :multiple => true do
projects.map { |p| p.tag_list}.flatten
end
end
Taglist is a method from act_as_taggable_on which returns an array of tags for each projects (f.e. ["foo", "bar"]). We index the project tags for the project members.
When, in our controller, we do:
Person.search() do
with(:project_tags).any_of(params[:tags])
end
This returns the right people. So far so good.
The Problem
We want to be able to search for multiple tags. So, per sunspot instructions, we pass along an array. The code looks roughly like this:
#tags_array= params[:tags].split(/ /)
Person.search() do
with(:project_tags).any_of(#tags_array)
end
Now Sunspot gives us every person as a result, no matter what tags we use! We have been testing this in the console like crazy, but can't understand where we are going wrong.
Any help would be appreciated!
Erwin
Ok we "solved" this ourselves and i'll report it back here in case anyone comes looking with the same question.
Somehow Sunspot doesn't like #tags_array in our search declaration, after some testing any #variable will not work. As soon as we changed it to:
tags_array= params[:tags].split(/ /)
Person.search() do
with(:project_tags).any_of(tags_array)
end
it worked.
Cheers,
Erwin

Adding title to rails route

I have List objects which are shown like this:
www.mysite.com/lists/123
Where 123 is the id of the list. What I would like to do is add the title of the list the url so it it more informative(for google or whatever). So I would like it to look like:
www.mysite.com/lists/123/title-of-list-number-123
How do you go about adding to a url like this? If you just enter:
www.mysite.com/lists/123 w/o the title, should it find the title and then redirect to a new route?
If you want to keep your find-calls as they are (by id), you could do the opposite of what mplacona suggested:
def to_param
"#{id}-#{title.parameterize}"
end
With this, your find(params[:id]) will work because it'll convert the string to an integer (can only succeed if the number is in the beginning of the string). So this is will actually work:
List.find("123-my-title")
and will be the same as
List.find(123)
Read more about this and other ways to accomplish this here: http://gregmoreno.ca/how-to-create-google-friendly-urls-in-rails/
The parameterize will automatically convert the string to a "pretty" url. Read more here: http://api.rubyonrails.org/classes/ActiveSupport/CoreExtensions/String/Inflections.html#M001367
If you want a bit more functionality, I'll suggest friendly_id aswell.
This article says exactly what you need to do accomplish this.
http://railscasts.com/episodes/63-model-name-in-url
UPDATE
Have a permalink added to your model, and save as follow to it:
def to_param
"#{permalink}-#{id}"
end
On your controller, instead of getting things by the id, get them by the pemalink:
#product = Product.find_by_permalink(params[:id])
And that's all you need.
The screen cast explains all the steps on how to do it.
You could also take a look at friendly id, if you're in the mood for a gem/plugin.

Resources