Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Kallikrates
Jul 7, 2002
Pro Lurker
http://xing.github.com/wysihtml5/

It's a very busy space theres probably a dozen more.

Adbot
ADBOT LOVES YOU

DankTamagachi
Jan 20, 2005
Tamagachi to your throat!
I'm trying to add a rating system to a microblog app I've written in rails. For some reason, the function below only updates "rating" for the first few times its called. After a while, it only updates rating_count! I've used a debugger and while the rating is changed in the "attributes" hash of the post object, it is not contained in the "changed attributes" hash of the same object, despite the value changing since the object was loaded.

As of now, this action (in posts controller) is being called via AJAX from a jQuery function. The data transmission is working great and I can see "temprating" holding the correct value when it is supposed to.

Any insight would be appreciated!

code:
  def vote

    @post = Post.find(params[:post_id])
    temprating = @post.rating * @post.rating_count
    @post.rating_count = @post.rating_count + 1
    temprating = temprating + params[:rating].to_i
    temprating = temprating  / @post.rating_count
    @post.rating =  temprating.to_i
    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Rating updated.' }
        format.json { render json: @post.rating  }
      else
        format.html { redirect_to @post, notice: 'Rating failed.' }
        format.json { render json: @post.errors }
      end
    end


  end

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

DankTamagachi posted:

I'm trying to add a rating system to a microblog app I've written in rails. For some reason, the function below only updates "rating" for the first few times its called. After a while, it only updates rating_count! I've used a debugger and while the rating is changed in the "attributes" hash of the post object, it is not contained in the "changed attributes" hash of the same object, despite the value changing since the object was loaded.

As of now, this action (in posts controller) is being called via AJAX from a jQuery function. The data transmission is working great and I can see "temprating" holding the correct value when it is supposed to.

Any insight would be appreciated!

code:
  def vote

    @post = Post.find(params[:post_id])
    temprating = @post.rating * @post.rating_count
    @post.rating_count = @post.rating_count + 1
    temprating = temprating + params[:rating].to_i
    temprating = temprating  / @post.rating_count
    @post.rating =  temprating.to_i
    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Rating updated.' }
        format.json { render json: @post.rating  }
      else
        format.html { redirect_to @post, notice: 'Rating failed.' }
        format.json { render json: @post.errors }
      end
    end


  end
Move all that poo poo to a model method. Also, don't store the average rating, store the counts of each rating. You're losing accuracy by converting it to integer, and you'll have a race condition if multiple clients are rating the same thing at the same time. You'll also have a double-vote problem here too.

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
What the previous poster said and additionally, take a look at http://api.rubyonrails.org/classes/ActiveRecord/CounterCache.html.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

DankTamagachi posted:

I'm trying to add a rating system to a microblog app I've written in rails.

Okay filling out my last post because I'm having coffee and it's a beautiful day out.

quote:

I'm trying to add a rating system to a microblog app I've written in rails. For some reason, the function below only updates "rating" for the first few times its called. After a while, it only updates rating_count! I've used a debugger and while the rating is changed in the "attributes" hash of the post object, it is not contained in the "changed attributes" hash of the same object, despite the value changing since the object was loaded.

This might be because you're truncating your average to an integer. For example, on a five-star scale, if I rate your post a one about six times, when you rate it five, it'll be 5/3:
code:
irb(main):012:0> (5.0 / 3)
=> 1.6666666666666667
irb(main):013:0> (5.0 / 3).to_i
=> 1
What you could do is store the ratings as floating point or decimal types, but you still have the problem with race conditions. What happens when I vote your post five and somebody else votes it one at the same time? It's non-deterministic, but in many cases one vote won't count.

Ruby code:
class CreateRatings < ActiveRecord::Migration
  def change
    create_table :ratings do |t|
      t.belongs_to :post
      t.belongs_to :user
      t.integer :rating

      t.timestamps
    end
    add_index :ratings, :post_id
    add_index :ratings, :user_id
    add_index :ratings, [:post_id, :user_id], unique: true
  end
end
Using a model like this, you can change your Post#vote_for_user(user, rating) implementation to:
Ruby code:
class Post
  has_many :ratings

  def vote_for_user(user_id, rating)
    rating = ratings.where(user_id: user_id).find_or_create

    rating.rating = 5
    rating.save
  end

  def rating
    ratings.average(:rating)
  end
end

Cocoa Crispies fucked around with this message at 17:40 on Nov 25, 2012

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
It should be noted that the find_or_create_by methods are being deprecated. For new Rails apps you should use Foo.where(:bar => 'baz').first_or_create.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Smol posted:

It should be noted that the find_or_create_by methods are being deprecated. For new Rails apps you should use Foo.where(:bar => 'baz').first_or_create.

Thanks, good to know!

The Journey Fraternity
Nov 25, 2003



I found this on the ground!
I should also probably point out that you have three different things that rating could be referring to in the vote_for_user method. :v:

Even though you have a local var as one of the three and the other two aren't being referred to, it still would be confusing in the future when things don't work as expected.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

The Journey Fraternity posted:

I should also probably point out that you have three different things that rating could be referring to in the vote_for_user method. :v:

Even though you have a local var as one of the three and the other two aren't being referred to, it still would be confusing in the future when things don't work as expected.

Yeah, it's one of those things where I wanted a demo and not necessarily production-quality code. I've had times at work where we spend an hour coming up with a name that doesn't conflict with some software component or domain noun, and it's hard.

"Ballot" might be reasonable I suppose.

DankTamagachi
Jan 20, 2005
Tamagachi to your throat!

Cocoa Crispies posted:

Yeah, it's one of those things where I wanted a demo and not necessarily production-quality code. I've had times at work where we spend an hour coming up with a name that doesn't conflict with some software component or domain noun, and it's hard.

"Ballot" might be reasonable I suppose.

Thank you all for the help here! I noticed this morning the same thing you did- simple math meant that if I was to_i'ing to INTs all the time, the rating bottomed out at 1 pretty quickly. D'oh!

I'm curious as to why you mentioned that this should be a "model function." I'm still getting used to this whole MVC framework, and the way I've been operating is basically putting only short attribute accessor-type functions in my models and all real methods in the controllers.

When should I put things in the model and when in the controller? Is there a good rule of thumb for stuff like this?

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.

DankTamagachi posted:

Thank you all for the help here! I noticed this morning the same thing you did- simple math meant that if I was to_i'ing to INTs all the time, the rating bottomed out at 1 pretty quickly. D'oh!

I'm curious as to why you mentioned that this should be a "model function." I'm still getting used to this whole MVC framework, and the way I've been operating is basically putting only short attribute accessor-type functions in my models and all real methods in the controllers.

When should I put things in the model and when in the controller? Is there a good rule of thumb for stuff like this?

Golden rule of MVC is: Fat models, thin controllers.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

DankTamagachi posted:

Thank you all for the help here! I noticed this morning the same thing you did- simple math meant that if I was to_i'ing to INTs all the time, the rating bottomed out at 1 pretty quickly. D'oh!

I'm curious as to why you mentioned that this should be a "model function." I'm still getting used to this whole MVC framework, and the way I've been operating is basically putting only short attribute accessor-type functions in my models and all real methods in the controllers.

When should I put things in the model and when in the controller? Is there a good rule of thumb for stuff like this?

If it's formatting data for or consuming data from a client, it goes in the controller. If it's about manipulating your data, it belongs in the model. For example, finding the post based on params[:post_id] and returning the post's rating in a JSON hash is a controller responsibility. Updating the average on and storing it belongs in the model.

The reasoning there is if you eventually have to change how rating works (i.e. if you change from ActiveRecord to Ripple and have to switch from a table to some kind of document-embedded CRDT) you can do it in the model, but keep the same controller and even the same unit tests on the model.

Oh My Science
Dec 29, 2008
I'm looking for an appointment booking gem or engine. I feel that something like this should already exist, but all I can find is https://github.com/Leveton/appointments which is poorly documented & tested.

Should I maybe look at an external service which offers an API?

Fillerbunny
Jul 25, 2002

so confused.
I have sort of a generic question about modelling a database. Is there any sort of rule of thumb about using STI versus polymorphic relationships?

Say for example you have a model/table called Manufacturers, and Manufacturers have many Products, and those Products share many common elements, but also, depending on the type, have specific elements that don't apply to all of them.

So for a given Manufacturer, say it's called "GloboChem," has a wide variety of Products, but for our purposes they have three types: Dolls, Shoes, and Condiments. All of these things share data elements like MSRP, ActualCost, SKU, etc., but each will also have elements that only pertain to their own type.

How do you design the models so you can say something like Manufacturers.Products and return all types?

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.
Not sure if this is the best place for this question, but here goes: I recently jumped ship from MacVim to Sublime Text 2, as the vintage (i.e. vim) mode is now close enough to vim for me, and it's a much nicer editor as a whole.

One complaint: the javascript syntax highlighting isn't quite up to par - for example, javascript dicts don't have the keys displayed in a different color the way they do in MacVim with Janus. Is there a way to fix this?

Kallikrates
Jul 7, 2002
Pro Lurker

quote:

elements that only pertain to their own type
boils down to how Okay you are with N*K null fields. STI also won't stop you from setting up type dependent relationships.

Otherwise you need to setup more complex has_many relationships.

We don't use STI, to hide attributes and generally only use it on Models that will share most attributes and functionality.

Fillerbunny
Jul 25, 2002

so confused.

Kallikrates posted:

boils down to how Okay you are with N*K null fields. STI also won't stop you from setting up type dependent relationships.

Otherwise you need to setup more complex has_many relationships.

We don't use STI, to hide attributes and generally only use it on Models that will share most attributes and functionality.

I'm mostly not okay with an unknown number of null fields. Especially once you get to a point where you're trying to retrofit and put things in fields where they really don't belong. Having worked mostly in MSSQL for the last n years, and knowing what I know about relational databases, I really prefer to break things out into detail tables and have as few null fields as possible.

But if that points to me using polymorphic relationships, then how would I set that up? I've read some how-to articles on it, but it just hasn't clicked yet.

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.

Fillerbunny posted:

I have sort of a generic question about modelling a database. Is there any sort of rule of thumb about using STI versus polymorphic relationships?

Say for example you have a model/table called Manufacturers, and Manufacturers have many Products, and those Products share many common elements, but also, depending on the type, have specific elements that don't apply to all of them.

So for a given Manufacturer, say it's called "GloboChem," has a wide variety of Products, but for our purposes they have three types: Dolls, Shoes, and Condiments. All of these things share data elements like MSRP, ActualCost, SKU, etc., but each will also have elements that only pertain to their own type.

How do you design the models so you can say something like Manufacturers.Products and return all types?

In my experience, using STI is fine if 1) you have a clear OO-style inheritance relationship among your models 2) you can reuse code and 3) you have as little as possible differing columns in the table, ideally none. I've seen STI implementations that innocently started with only one extra column in the subclass that have over the years evolved into intangible messes that nobody wants to touch. Some of the subclasses probably don't have any common columns at this point.

Also, if you have some gems that monkeypatch AR, I'd expect a lot of them not to work well with STI.

Smol fucked around with this message at 00:56 on Nov 27, 2012

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Lexicon posted:

Not sure if this is the best place for this question, but here goes: I recently jumped ship from MacVim to Sublime Text 2, as the vintage (i.e. vim) mode is now close enough to vim for me, and it's a much nicer editor as a whole.

One complaint: the javascript syntax highlighting isn't quite up to par - for example, javascript dicts don't have the keys displayed in a different color the way they do in MacVim with Janus. Is there a way to fix this?

Try out some different color schemes, sometimes they have different syntax highlighting implementations. Or you can extend the js definition yourself. Sublime also accepts Text-mate formatted color palettes iirc (.tmlanguage extension?).

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.
^ Ok will do, thanks.

Oh My Science
Dec 29, 2008

Fillerbunny posted:

I have sort of a generic question about modelling a database. Is there any sort of rule of thumb about using STI versus polymorphic relationships?

If you have a railscast account Ryan just posted an episode on this very subject. I'll give it a watch and get back to you.

STI and Polymorphic Associations

Fillerbunny
Jul 25, 2002

so confused.

Oh My Science posted:

If you have a railscast account Ryan just posted an episode on this very subject. I'll give it a watch and get back to you.

STI and Polymorphic Associations

I don't have a pro account, sadly. That sounds like it's right up my alley.

Everything I've read so far says to avoid STI. My gut is telling me to avoid STI. The only thing holding me back from using polymorphic associations is, "I don't get it."

Oh My Science posted:

Ryan has a revised polymorphic episode, Polymorphic Association (revised), which may give you some insight. It's free.

poo poo never mind, forgot revised episodes cost $$ too. sorry.

Thanks for following up. That particular polymorphic method that's shown in the revised video's description--the one where there's a particular table, and it can be referenced in different types of tables--I get that one. But I can't seem to make the shift happen in my mind to apply it to the model I described above.

Fillerbunny fucked around with this message at 22:08 on Nov 26, 2012

Oh My Science
Dec 29, 2008

Fillerbunny posted:

I don't have a pro account, sadly. That sounds like it's right up my alley.

Everything I've read so far says to avoid STI. My gut is telling me to avoid STI. The only thing holding me back from using polymorphic associations is, "I don't get it."

Ryan has a revised polymorphic episode, Polymorphic Association (revised), which may give you some insight. It's free.

poo poo never mind, forgot revised episodes cost $$ too. sorry.

Oh My Science fucked around with this message at 21:44 on Nov 26, 2012

Physical
Sep 26, 2007

by T. Finninho
Cross postin'

Physical posted:

Regular Expression question:
I want to match only whats inbetween the commas, not a part of it. Here's what I have:

Ruby code:
str = "12, 5, 9"
str =~ /,?2,?/ #finds the 2 in 12, which isn't what I want.
I don't want it to detect the 2 in 12. How do I do that?

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
I'm not sure what you mean. Do you want to match or perhaps capture something? What exactly, everything between the first and the second commas?

If it helps though, your current regular expression means "zero or one commas, 2, zero or one commas" so any string that contains the number 2 will be trivially recognized by the regex.

Obsurveyor
Jan 10, 2003

Physical posted:

Cross postin'

/,??([^,]*),??/

Is this it? You were a bit vague. Give expected output, given input instead of just saying what you don't want, which isn't helpful.

Physical
Sep 26, 2007

by T. Finninho
Well I thought the comment explained it. I was getting false postitives if the string contained 12 or 22 or 32 or 21 or etc. What I wanted was it to find ONLY 2. I got my answer in the other thread though:

Sedro posted:

You can use \b to match a word boundary. For example, ,?(\b2\b),? will have zero matches against your string. The regex ,?(\b12\b),? will match, and the first capture group will have the value 12. And you probably don't need to match the commas, which leaves you with \b2\b
So in a comma separated string, this \b2\b will return nil if string = "12, 1, 3, 52" which is what I want.

Physical fucked around with this message at 01:49 on Nov 27, 2012

Sparta
Aug 14, 2003

the other white meat
My company is offering a nice finders-fee to any of us who recruit a ruby/rails developer. I've been posting ads on cl, responding to resumes, etc, but I have yet to even get a response back.

How do I find rails developers looking for a job?

Pardot
Jul 25, 2001




Physical posted:

Well I thought the comment explained it. I was getting false postitives if the string contained 12 or 22 or 32 or 21 or etc. What I wanted was it to find ONLY 2. I got my answer in the other thread though:

So in a comma separated string, this \b2\b will return nil if string = "12, 1, 3, 52" which is what I want.

For future reference, http://rubular.com/ is the best for quickly iterating on regular expressions.

Kallikrates
Jul 7, 2002
Pro Lurker

Sparta posted:

My company is offering a nice finders-fee to any of us who recruit a ruby/rails developer. I've been posting ads on cl, responding to resumes, etc, but I have yet to even get a response back.

How do I find rails developers looking for a job?

Allow remote workers.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Sparta posted:

My company is offering a nice finders-fee to any of us who recruit a ruby/rails developer. I've been posting ads on cl, responding to resumes, etc, but I have yet to even get a response back.

How do I find rails developers looking for a job?


Kallikrates posted:

Allow remote workers.

We do this, and it's still hard to find good people. Rails is in demand right now, so much so that people who are literally too retarded to ask regexp questions but know Rails keep jobs.

A MIRACLE
Sep 17, 2007

All right. It's Saturday night; I have no date, a two-liter bottle of Shasta and my all-Rush mix-tape... Let's rock.

Cocoa Crispies posted:

Rails is in demand right now, so much so that people who are literally too retarded to ask regexp questions but know Rails keep jobs.

What does this mean? That someone has a problem easily solved by Regex but can't formulate a question around it? And how do you learn Ruby and not learn to use Regex at least a little bit?

Physical
Sep 26, 2007

by T. Finninho

Cocoa Crispies posted:

We do this, and it's still hard to find good people. Rails is in demand right now, so much so that people who are literally too retarded to ask regexp questions but know Rails keep jobs.
I just asked a regex question :ohdear:

Kallikrates
Jul 7, 2002
Pro Lurker

Cocoa Crispies posted:

We do this, and it's still hard to find good people. Rails is in demand right now, so much so that people who are literally too retarded to ask regexp questions but know Rails keep jobs.

I guess be willing to pay for skill. I recently shopped around what was available around D.C. (very small ruby/rails market and community for less than mid level positions) and I was out of the price range everywhere. Granted I'm more of a generalist and have used rails as mostly API's for Mobile app's so maybe my skills weren't a full fit.

So for now I'm staying where I'm at. This leaves out the places where the interviewing/follow-up process was so disorganized, that I simply stopped picking up their calls/emails.

There are devs out there with ears and eyes open. Hiring devs is hard and it's all the companies fault.

manero
Jan 30, 2006

Sparta posted:

My company is offering a nice finders-fee to any of us who recruit a ruby/rails developer. I've been posting ads on cl, responding to resumes, etc, but I have yet to even get a response back.

How do I find rails developers looking for a job?

Do you have a local Ruby user group? I help organize the local Ruby user group and it's probably the best way to network and find people looking.

That said, the local market is pretty tight as well, and I know a number of places who need developers but can't find any.

Physical
Sep 26, 2007

by T. Finninho
Local User Group eh? I maybe should find and join groups like that.

Physical
Sep 26, 2007

by T. Finninho
Ruby code:
obj #just some random object
field = :name #some arbitrary member variable of that object

obj.(field.constantize) #this is the important part that I am looking for an answer to
Desired results are that the above code will equate to the following
Ruby code:
obj.name 
but the above definately does not work. The reason I am trying to do this is because I have to handle a field name being passed to this function as a string or symbol. I suppose
Ruby code:
obj.send(field)  
would work but I'd still like to know if there is a constantize way to do it.

Obsurveyor
Jan 10, 2003

Physical posted:

Ruby code:
obj #just some random object
field = :name #some arbitrary member variable of that object

obj.(field.constantize) #this is the important part that I am looking for an answer to
Desired results are that the above code will equate to the following
Ruby code:
obj.name 
but the above definately does not work. The reason I am trying to do this is because I have to handle a field name being passed to this function as a string or symbol. I suppose
Ruby code:
obj.send(field)  
would work but I'd still like to know if there is a constantize way to do it.

constantize only works on strings so you'll have to convert it to a string. I haven't had to use it before and it's a Rails only thing but it looks like constantize only returns Classes and Modules, so it's not going to help you with field names.

Obsurveyor fucked around with this message at 17:01 on Nov 29, 2012

Physical
Sep 26, 2007

by T. Finninho

Obsurveyor posted:

constantize only works on strings so you'll have to convert it to a string. I haven't had to use it before and it's a Rails only thing but it looks like constantize only returns Classes and Modules, so it's not going to help you with field names.
Yea it looks like you are right, the string vs symbol wasn't the hard part, I could just to_s the symbol if I had to. I'm just using obj.send()

Here another part of the same process, you pass it an object and a field as a symbol or string or whatever and it builds a string for you (it's for a select_tag generator)
Ruby code:
def example(obj, field)
     obj.class.to_s.underscore + "[#{field}]"
end
Probably could clean this up a little more

Adbot
ADBOT LOVES YOU

prom candy
Dec 16, 2005

Only I may dance
Can you explain why you're not using send?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply