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
Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Physical posted:

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.

What the gently caress are you trying to do, from a high level?

Adbot
ADBOT LOVES YOU

Obsurveyor
Jan 10, 2003

Can someone explain why this isn't working the way I expect?

Ruby code:
# example data structure from ActiveRecord
#
#<Vote id: 1, user_id: 1, allocation_id: 4, idea_id: 7, 
# created_at: "2012-11-29 16:32:40", updated_at: "2012-11-29 16:32:40", 
# lock_version: 0, comments: nil>
#

# assume Enterprise.first.votes has 20 entries like above and 5 of them
# have an idea_id greater than 5.
#
>> Enterprise.first.votes.count { |v| v.idea_id > 5 }
=> 20
#
# Why isn't it 5???
Checking if idea_id is greater than 5 is just an example, it doesn't matter what you put there, even just false will still return the entire count of the votes array.

This works as expected:

Ruby code:
>> plain_array = [1, 2, 2, 3, 4]
=> [1, 2, 2, 3, 4]
>> plain_array.count { |i| i == 2 }
=> 2

Physical
Sep 26, 2007

by T. Finninho

prom candy posted:

Can you explain why you're not using send?
I am using send. Why didn't I want to? There's not really a good reason for that, it was out of curiosity.

Cocoa Crispies posted:

What the gently caress are you trying to do, from a high level?
How high do you want? The highest I can give is that I am offering a way for the user to manage the order in which their forms and show pages display their fields. So I am trying to write an abstract system the inspects the current model's fields, and from their type figures out what kind of input field to make for them.

Obsurveyor posted:

Can someone explain why this isn't working the way I expect?

Ruby code:
# example data structure from ActiveRecord
#
#<Vote id: 1, user_id: 1, allocation_id: 4, idea_id: 7, 
# created_at: "2012-11-29 16:32:40", updated_at: "2012-11-29 16:32:40", 
# lock_version: 0, comments: nil>
#

# assume Enterprise.first.votes has 20 entries like above and 5 of them
# have an idea_id greater than 5.
#
>> Enterprise.first.votes.count { |v| v.idea_id > 5 }
=> 20
#
# Why isn't it 5???
Checking if idea_id is greater than 5 is just an example, it doesn't matter what you put there, even just false will still return the entire count of the votes array.

This works as expected:

Ruby code:
>> plain_array = [1, 2, 2, 3, 4]
=> [1, 2, 2, 3, 4]
>> plain_array.count { |i| i == 2 }
=> 2
Is count's behavior different since it is AR instead of an array?

Obsurveyor
Jan 10, 2003

Physical posted:

Is count's behavior different since it is AR instead of an array?

First thing I thought of, so I checked:

Ruby code:
>> Enterprise.first.votes.class
=> Array
:confused:

Kallikrates
Jul 7, 2002
Pro Lurker
Count works different in AR.
https://github.com/rails/rails/blob/f8f4ac91203506c94d547ee0ef530bd60faf97ed/activerecord/lib/active_record/relation/calculations.rb#L56
It always falls through to a db request.

Kallikrates fucked around with this message at 21:03 on Nov 29, 2012

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Physical posted:

How high do you want? The highest I can give is that I am offering a way for the user to manage the order in which their forms and show pages display their fields. So I am trying to write an abstract system the inspects the current model's fields, and from their type figures out what kind of input field to make for them.

Ruby code:
sort_field = params[:sort_by].to_sym
sort_field = :created_at unless Model.attribute_names.include?(sort_field.to_s)
Model.limit(20).order(sort_field)

Obsurveyor
Jan 10, 2003


Well that sucks. I guess I'll just stick with each then. Thanks.

Physical
Sep 26, 2007

by T. Finninho

Obsurveyor posted:

Well that sucks. I guess I'll just stick with each then. Thanks.
You could do a to_a on it, and I think that will make it behave like how you wanted.

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

Obsurveyor posted:

Ruby code:
>> Enterprise.first.votes.count { |v| v.idea_id > 5 }
=> 20
Checking if idea_id is greater than 5 is just an example, it doesn't matter what you put there, even just false will still return the entire count of the votes array.


Ruby code:
Enterprise.first.votes.where('idea_id > ?', 5).count
Since it's falling back to the database, use SQL.

Obsurveyor
Jan 10, 2003

Physical posted:

You could do a to_a on it, and I think that will make it behave like how you wanted.

Thanks, that makes it work the way I expected.

Cocoa Crispies posted:

Ruby code:
Enterprise.first.votes.where('idea_id > ?', 5).count
Since it's falling back to the database, use SQL.

Thanks for clarifying how count is supposed to be used with AR. Unfortunately, it doesn't work in this case. I really do want to enumerate all the votes in my actual use case because I'm interested in a field in the idea model that each vote belongs to.

Fillerbunny
Jul 25, 2002

so confused.
Shouldn't you be able to chain that AR object returned from the where method to find the idea objects you're interested in?

Obsurveyor
Jan 10, 2003

Fillerbunny posted:

Shouldn't you be able to chain that AR object returned from the where method to find the idea objects you're interested in?

I don't think so. This is the real code using the tip from Physical:

Ruby code:
def unreleased_votes
  votes.to_a.count { |v| !v.idea.released? }
end
This looks a lot better than the huge votes.each do...end I had before.

Fillerbunny
Jul 25, 2002

so confused.
That's probably faster than hitting the database anyway.

Physical
Sep 26, 2007

by T. Finninho

Fillerbunny posted:

That's probably faster than hitting the database anyway.
Yea probably. I crashed our DB at another job (using php) because I tried to use joins and group bys and some calculated fields in the sql queries thinking the DB engine would handle it faster than post processing. Lesson learned, just because the features are available doesn't mean you should use the.

enki42
Jun 11, 2001
#ATMLIVESMATTER

Put this Nazi-lover on ignore immediately!

Obsurveyor posted:

I don't think so. This is the real code using the tip from Physical:

Ruby code:
def unreleased_votes
  votes.to_a.count { |v| !v.idea.released? }
end
This looks a lot better than the huge votes.each do...end I had before.

This looks like it works and is probably reasonable if you have a limited number of votes, but you should be able to do the following if you still want to pull this from the DB:

Ruby code:
def unreleased_votes
  votes.joins(:idea).where(idea: { released: false }).count
end

quote:

That's probably faster than hitting the database anyway.

Actually, unless there's an include that's being omitted for brevity, it's probably way slower and an N+1 to boot. You're going to make a seperate DB call for each and every vote (to pull the idea). I didn't even notice that when I originally wrote the reply, but you should absolutely fix that at a bare minimum, that's the sort of thing that WILL bite you in the rear end if you're not careful with it.

enki42 fucked around with this message at 12:29 on Nov 30, 2012

Pardot
Jul 25, 2001




Physical posted:

just because the features are available doesn't mean you should use the.

That greatly depends on which database.

Fillerbunny
Jul 25, 2002

so confused.

enki42 posted:

This looks like it works and is probably reasonable if you have a limited number of votes, but you should be able to do the following if you still want to pull this from the DB

This is actually a huge point. I had assumed that given the sample data that the set you were working with would be small, but if you have a number of votes greater than say 100 or so, you're absolutely going to want to pare that down at the database level. The line of thinking like, "just give me everything and I'll deal with sorting it out" is a messy one and can lead to serious issues.

Obsurveyor
Jan 10, 2003

enki42 posted:

Ruby code:
def unreleased_votes
  votes.joins(:idea).where(idea: { released: false }).count
end

Thanks for this. However, released? is something I had to write. How do I check for null instead of false? nil? To be honest, this is the most I have had to deal with ActiveRecord since I started using ruby. So far, I haven't had any use for a relational db, mongodb has been well suited to everything I have done. I have plenty of legacy PHP stuff that uses relational dbs and needs their functionality, just nothing with ruby so far.

enki42 posted:

Actually, unless there's an include that's being omitted for brevity, it's probably way slower and an N+1 to boot. You're going to make a seperate DB call for each and every vote (to pull the idea). I didn't even notice that when I originally wrote the reply, but you should absolutely fix that at a bare minimum, that's the sort of thing that WILL bite you in the rear end if you're not careful with it.

Fillerbunny posted:

This is actually a huge point. I had assumed that given the sample data that the set you were working with would be small, but if you have a number of votes greater than say 100 or so, you're absolutely going to want to pare that down at the database level. The line of thinking like, "just give me everything and I'll deal with sorting it out" is a messy one and can lead to serious issues.

Yeah, I'm well aware of the ramifications of doing it the way I am. I'll switch it out for the single database call if it becomes an issue. Pre-mature optimization and all. Once I check out how the production database looks, I'll make the call on which one to use. I didn't write this app, and this is not something that is going to be used when users interact with it, so it's not a big deal if it's a little slower but more readable if I have to come back and modify it in the future.

Obsurveyor fucked around with this message at 14:59 on Nov 30, 2012

enki42
Jun 11, 2001
#ATMLIVESMATTER

Put this Nazi-lover on ignore immediately!

quote:

Thanks for this. However, released? is something I had to write. How do I check for null instead of false? nil? To be honest, this is the most I have had to deal with ActiveRecord since I started using ruby. So far, I haven't had any use for a relational db, mongodb has been well suited to everything I have done. I have plenty of legacy PHP stuff that uses relational dbs and needs their functionality, just nothing with ruby so far.

Yup, you can just pass :released => nil and it will do the right check. If you have to check false or nil, unfortunately it can get a little gross. You need to either use Arel or the following SQL fragment:

code:
   where("released = false OR released IS null")
due to the slight weirdness of NULL in SQL.

quote:

Yeah, I'm well aware of the ramifications of doing it the way I am. I'll switch it out for the single database call if it becomes an issue. Pre-mature optimization and all. Once I check out how the production database looks, I'll make the call on which one to use. I didn't write this app, and this is not something that is going to be used when users interact with it, so it's not a big deal if it's a little slower but more readable if I have to come back and modify it in the future.

Fixing N+1's doesn't count as "premature optimization". At the very least include the associated model when you pull down the votes. There's really no reason that you should ever have one in your code, and it takes really small amounts of records before you start noticing significant slowdowns.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal
Hey this is a bit off topic, but NewRelic (a suite that offers application monitoring, performance monitoring, and other stuff) is offering a free t-shirt to any new user who signs up: http://www.newrelic.com/ and deploys their app (click the link at the top). I deployed on a Rails Tutorial app I'm running on Heroku and it's monitoring wonderfully, was a ridiculously easy install (gem 'newrelic' or something), and I just ordered my free shirt.

I'm not affiliated or anything, but thought some people might want a free 'nerd life' t-shirt. The application seems like it could be handy as well.

Edit:

Instructions for the shirt if you want it:
1. Signup (free)
2. Login to your newrelic account. There's installation information for whatever your application language is (Ruby, PHP, etc)
3. Install the gem, deploy to a production service. I visited the application to make sure it had some data to send to the server. There's a newrelic.yml (or similar) file you can quickly edit for configuration settings.
3. Send an e-mail from the email you signed up with, and they'll send you a code
email: marketing@newrelic.com
subject: I've already deployed! I want my Nerd Life t-shirt.‏
4. Enter the code here: http://get.printfection.com/nerdlife/g2660/ and enter your shipping address etc.

Again I apologize if this is in the wrong section; I know we have a freebies forum but it seemed a little too niche for the general forums.

Knyteguy fucked around with this message at 01:34 on Dec 4, 2012

Novo
May 13, 2003

Stercorem pro cerebro habes
Soiled Meat

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?

Have you tried GitHub / StackOverflow's jobs page? I check those when I'm bored and thinking about moving on. Just don't do what Rumblefish did: contacted me out of the blue, refused to say how they found me, complained about how hard it was to find "good developers" then stopped talking to me entirely without so much as a "we dont' think you'd be a good match because _______" after I agreed to talk with them. That type of poo poo is not going to make finding good developers any easier.

raej
Sep 25, 2003

"Being drunk is the worst feeling of all. Except for all those other feelings."
On a form, is there an easy way to pass values as integers instead of strings?

My scenario is this:
I have a model called "Artist" which has name, desc, artist_id. This model has many Albums.

I have another model called "Album" which has name, desc, album_id, artist_id. Each album belongs to an Artist.

In the album/new form, I need to pass the artist_id to the controller to create the object. Because it's passing the artist_id as a string, I get the error:

"Artist(#46690788) expected, got String(#17528052)"

Better yet would be a way to just type in the artist and search artist.name for a match and send an error if there is no match.

As it stands though, the form submits everything as params[:album] with each part a string.

Any help would be appreciated!

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.

raej posted:

On a form, is there an easy way to pass values as integers instead of strings?

My scenario is this:
I have a model called "Artist" which has name, desc, artist_id. This model has many Albums.

I have another model called "Album" which has name, desc, album_id, artist_id. Each album belongs to an Artist.

In the album/new form, I need to pass the artist_id to the controller to create the object. Because it's passing the artist_id as a string, I get the error:

"Artist(#46690788) expected, got String(#17528052)"

Better yet would be a way to just type in the artist and search artist.name for a match and send an error if there is no match.

As it stands though, the form submits everything as params[:album] with each part a string.

Any help would be appreciated!

Well I think it comes in as a string because it's coming to the server as a POST request, right? So a user could submit a non-integer, then your app processes it as one, and bam, 500 error. So in this case it might be prudent to try to convert it to an integer before processing it, using `.to_i' or similar.

enki42
Jun 11, 2001
#ATMLIVESMATTER

Put this Nazi-lover on ignore immediately!

raej posted:

On a form, is there an easy way to pass values as integers instead of strings?

My scenario is this:
I have a model called "Artist" which has name, desc, artist_id. This model has many Albums.

I have another model called "Album" which has name, desc, album_id, artist_id. Each album belongs to an Artist.

In the album/new form, I need to pass the artist_id to the controller to create the object. Because it's passing the artist_id as a string, I get the error:

"Artist(#46690788) expected, got String(#17528052)"

Better yet would be a way to just type in the artist and search artist.name for a match and send an error if there is no match.

As it stands though, the form submits everything as params[:album] with each part a string.

Any help would be appreciated!

I don't think the problem you're running into has to do with strings vs. numbers. Rails isn't expecting a number, it's expecting a full-fledged Artist object. It looks like your form might be passing in a key named "artist" rather than a key named "artist_id". Could you maybe post what parameters are being passed into the form (from the logs) as well as the relevant portions of the view?

Physical
Sep 26, 2007

by T. Finninho
So this probably won't work but I wanted to ask anyway. I just implemented some eager loading and it works fine. In an effort to cache some more data for a table that doesn't have a model relationship, but has a semantic one, I thought I could grab all the objects by running a query and then RoR would magically realize "oh this stuff has already been grabbed." But it doesn't seem to work, since the queries aren't exactly the same. Is it possible?

Obsurveyor
Jan 10, 2003

Well this sure does explain a lot:

http://spin.atomicobject.com/2012/11/06/is-your-application-running-with-ruby-slow/

I run my development machine in a VM so it's already slow. However, it seems rvm has been compiling ruby without optimizations on both my development and the real production machine. Looks like I have more stuff to do this weekend.

noskill
Dec 6, 2012

OMCK

Physical posted:

So this probably won't work but I wanted to ask anyway. I just implemented some eager loading and it works fine. In an effort to cache some more data for a table that doesn't have a model relationship, but has a semantic one, I thought I could grab all the objects by running a query and then RoR would magically realize "oh this stuff has already been grabbed." But it doesn't seem to work, since the queries aren't exactly the same. Is it possible?

Generally speaking, caching and "magical" don't work together very well.

There used to be somewhat popular gem called cache-money which did exactly what you describe. I've used it and it worked pretty well but developers stopped supporting it around time when Rails 3 was released (and nobody took over project) so it's pretty much gone at this point.

I've also tried something called record-cache but it wasn't good enough for what I was trying to do but it might work well for you (I don't really know how complicated and/or easy to cache your queries are).

What I personally ended up doing is moving business logic in models into separate methods and wrapping them up in generic caching method, something along the lines of this:

code:
def fetch_data(param)
  # create a key that identified this particular set of objects somehow
  key = "data_#{param}"
  
  Rails.cache.fetch(key, :expires_in => 5.minutes) do
    # actual logic goes here
  end
end
Then I simply call fetch_data method when I need it.

Kallikrates
Jul 7, 2002
Pro Lurker
rails has pretty good caching built in, active record models respond to cache_key https://github.com/rails/rails/blob/ceb33f84933639d3b61aac62e5e71fd087ab65ed/activerecord/lib/active_record/integration.rb#L37

you might be able to override it to provide a 'broader' key or write your own cache.fetch.

Integration with cache is also nice in that cache fetch will query based on the cache_key, but also execute a block on cache misses and store that result.

Ruby code:
cache.fetch("city")   # => nil
cache.fetch("city") do
  "Duckburgh"
end
cache.fetch("city")   # => "Duckburgh"

Flobbster
Feb 17, 2005

"Cadet Kirk, after the way you cheated on the Kobayashi Maru test I oughta punch you in tha face!"
So if I have text_fields on a page that contain dates that I want formatted differently from the default yyyy-mm-dd, what's the Rails 3 way of making sure those dates persist properly in the database when the form is submitted? I'm halfway there -- I can get the dates displayed the way I want them on the page, but when it submits, it appears to parse the date incorrectly.

Here's a FormBuilder extension method I wrote to create my fields:

Ruby code:
class ActionView::Helpers::FormBuilder
  def date_field(attribute, *args, &block)
    options = args.extract_options!
    options[:value] = object[attribute] &&
      I18n.l(object[attribute].to_date).gsub(/\s+/, ' ')
    if options[:class]
      options[:class] = options[:class] + ' datepicker'
    else
      options[:class] = 'datepicker'
    end
    text_field(attribute, *(args << options), &block)
  end
end
So, now whenever I use a date_field I get the date converted using my locale's format, which in my en.yml file is:

code:
en:
  date:
    formats:
      default: "%m/%d/%Y"
So far so good -- when the page is rendered, the date looks right. But when I submit it, the date isn't getting parsed correctly, because the month and day are flipped. If I put in "05/08/2013" into the field, the database contains "2013-08-05". If I put in a day higher than 12, the database column is null because it tried to parse the date as a month.

Information that I can dig up online seems to conflict and change from version to version. I tried putting this in an initializers file:

Ruby code:
Time::DATE_FORMATS.merge!(db: '%m/%d/%Y')
Date::DATE_FORMATS.merge!(db: '%m/%d/%Y')
But that had no effect. What piece am I missing here?

(Edit) SOLUTION! Apparently I'd have to override the setters in my model to parse the dates correctly. But I finally discovered the "delocalize" gem which apparently monkeypatches input fields so that I don't have to. I'll leave this here in case anyone else has the same problem.

Flobbster fucked around with this message at 22:39 on Dec 8, 2012

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
E: Found the error, my cookie jar wasn't loading right

Paul MaudDib fucked around with this message at 01:42 on Dec 11, 2012

Bodybuilding Virgin 420
Aug 29, 2000

f

Bodybuilding Virgin 420 fucked around with this message at 01:48 on Jul 7, 2014

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
Nice work. For clarity and consistency though, you should give them a "Path" suffix. Something like "/foo" is not an URL and Rails will call it foo_path as well.

Bodybuilding Virgin 420
Aug 29, 2000

Smol posted:

Nice work. For clarity and consistency though, you should give them a "Path" suffix. Something like "/foo" is not an URL and Rails will call it foo_path as well.

Good idea, I'll change it later.

Physical
Sep 26, 2007

by T. Finninho
edit: New question, what does ||= operator do?
Ruby code:
    def collection
      @projects ||= end_of_association_chain.paginate(:page => params[:page])
    end

e: nevermind, I found the answer http://paulsturgess.co.uk/articles/70-using-or-equals-to-set-variables-in-ruby-on-rails It's always so hard to do google searches for operators, as google thinks I mean to use them as operators instead of search strings.

I'm using inherit_resources and for one controller I want the edit action to not restrict it's search to results that ONLY have the current_account as an account_id. Right now, I get

quote:

ActiveRecord::RecordNotFound (Couldn't find MyCustomModel with id=4 [WHERE `my_custom_model`.`account_id` = 1]):


Rendered /.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /.rvm/gems/ruby-1.9.2-p290/gems/actionpack-3.1.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
I basically need to drop the "where account_id = 1"

In my edit I have tried a super do |format| to override it but it doesn't work.

e:Ah got it, had to override def resource It gets a little mention here https://github.com/josevalim/inherited_resources under "overwriting defaults" but doesn't seem that explicit so I went and sought it out in the code here https://github.com/josevalim/inherited_resources/blob/master/lib/inherited_resources/base_helpers.rb

Physical fucked around with this message at 16:58 on Dec 11, 2012

raej
Sep 25, 2003

"Being drunk is the worst feeling of all. Except for all those other feelings."
Alright, I've ran into another snag that's been driving me up the walls.

I've gone through the railstutorial.org tutorial and have a site up and running.

I've created Brewery and Beer models with Beers being children of Breweries.

What I'm trying to do it create a catalog of cellared beers for users leveraging the relationships model of chapter 11 of the tutorial.

The basic concept is creating a table with Followed_ID and Following_ID to keep track of users following other users, and a reverse_relationships table for to get a user's followers.

Since I'll be having users "cellar" beer models instead of other users, I'm running into issues with ActiveRecord::AssociationTypeMismatch

Cellaredbeer model:
Ruby code:
class Cellaredbeer < ActiveRecord::Base
  attr_accessible :cellared_id, :cellarer_id

  belongs_to :cellarer_id, class_name: "User"
  belongs_to :cellared_id, class_name: "Beer"

  validates :cellarer_id, presence: true
  validates :cellared_id, presence: true
end
User model (abbrevaited):
Ruby code:
class User < ActiveRecord::Base
  attr_accessible :name, :email, :password, :password_confirmation

  has_many :cellaredbeers, foreign_key: "cellarer_id", dependent: :destroy
  has_many :cellared_beers, through: :cellaredbeers, source: :cellared_id

  def cellaring?(beer)
    self.cellaredbeers.find_by_cellared_id(beer.id)
  end

  def cellar!(beer)
    self.cellaredbeers.create!(cellared_id: beer.id)
  end

  def uncellar!(beer)
    self.cellaredbeers.find_by_cellared_id(beer.id).destroy
  end

end
Beer model (abbreviated):
Ruby code:
class Beer < ActiveRecord::Base
  belongs_to :brewery
  has_many :cellaredbeers, foreign_key: "cellared", dependent: :destroy
  has_many :cellarers, through: :cellaredbeers, source: :cellarer_id
end
And the CellaredbeersController:
Ruby code:
class CellaredbeersController < ApplicationController
  before_filter :signed_in_user

  def create
    @beer = Beer.find(params[:cellaredbeer][:cellared_id])
    current_user.cellar!(@beer)
    respond_to do |format|
      format.html { redirect_to @beer }
      format.js
    end
  end
I'm getting the following error on my form for adding a beer to a cellar:
User(#47247564) expected, got Fixnum(#3598368)

Form:
Ruby code:
<%= form_for(current_user.cellaredbeers.build(cellared_id: @beer)) do |f| %>
  <div><%= f.hidden_field :cellared_id %></div>
  <%= f.submit "Cellar", class: "btn btn-large btn-warning" %>
<% end %>
I can infer from the error that something is expecting a User, but instead getting a fixnum (most likely passing an ID) but I can't narrow down what is expecting a User, or what is passing the ID?

The idea is to have this button on a beer page to "add the beer" to the logged in user's cellar. So when the button is clicked, it takes the beer's ID and the current_user's ID and adds a row to the cellaredbeers table.

What am I missing here?

raej fucked around with this message at 00:04 on Dec 12, 2012

Obsurveyor
Jan 10, 2003

raej posted:

User(#47247564) expected, got Fixnum(#3598368)

Are these really the traces you're getting from errors? Don't you get a line number and filename with your errors to check? I'd go insane if this was normal rails/ruby error handling(it's not).

raej
Sep 25, 2003

"Being drunk is the worst feeling of all. Except for all those other feelings."

Obsurveyor posted:

Are these really the traces you're getting from errors? Don't you get a line number and filename with your errors to check? I'd go insane if this was normal rails/ruby error handling(it's not).

Here's the whole thing:
code:
 ActiveRecord::AssociationTypeMismatch in Beers#show

Showing c:/RailsInstaller/Ruby1.9.3/RailsApps/sample_app/app/views/beers/_cellar.html.erb where line #1 raised:

User(#47247564) expected, got Fixnum(#3598368)

Extracted source (around line #1):

1: <%= form_for(current_user.cellaredbeers.build(cellared_id: @beer)) do |f| %>
2:   <div><%= f.hidden_field :cellared_id %></div>
3:   <%= f.submit "Cellar", class: "btn btn-large btn-warning" %>
4: <% end %>

Trace of template inclusion: app/views/beers/show.html.erb

Rails.root: c:/RailsInstaller/Ruby1.9.3/RailsApps/sample_app
Application Trace | Framework Trace | Full Trace

app/views/beers/_cellar.html.erb:1:in `_app_views_beers__cellar_html_erb___496998550_46746960'
app/views/beers/show.html.erb:27:in `_app_views_beers_show_html_erb__1014788976_46673556'

Request

Parameters:

{"id"=>"30"}

Show session dump

Show env dump
Response

Headers:

None
Changing the _cellar.html.erb partial from
Ruby code:
<%= form_for(current_user.cellaredbeers.build(cellared_id: @beer)) do |f| %>
to
Ruby code:
<%= form_for(current_user.cellaredbeers.build(cellared_id: @beer.id)) do |f| %>
changed the main error to
Beer(#47716920) expected, got Fixnum(#3598368)

I'm expecting the form to send the ID of the beer to the cellarbeers controller which should create the instance of the beer with, and then send the beer object to the user model to cellar
Ruby code:
  def create
    @beer = Beer.find(params[:cellaredbeer][:cellared_id])
    current_user.cellar!(@beer)
    respond_to do |format|
      format.html { redirect_to @beer }
      format.js
    end
  end
user method:
Ruby code:
  def cellar!(beer)
    self.cellaredbeers.create!(cellared_id: beer.id)
  end


Edit: I redid my model using less 'out-there' and more rails happy foreign keys which seems to have solved this issue.

raej fucked around with this message at 07:45 on Dec 12, 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.

Github published a Ruby styleguide today:

https://github.com/styleguide/ruby

Nothing that most of the people (including myself) in this thread aren't already following as far as I can tell. But I did learn that `for loops` don't introduce a new scope for their iterators!

Pardot
Jul 25, 2001




A MIRACLE posted:

Github published a Ruby styleguide today:

https://github.com/styleguide/ruby

Nothing that most of the people (including myself) in this thread aren't already following as far as I can tell. But I did learn that `for loops` don't introduce a new scope for their iterators!

I don't think I've ever used a for loop in ruby. I'm trying to think of a time, and just can't.

Adbot
ADBOT LOVES YOU

Doc Hawkins
Jun 15, 2010

Dashing? But I'm not even moving!


For loops are training wheels for java babies.

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