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
plasticbugs
Dec 13, 2006

Special Batman and Robin
I have a model setup question. I'm creating a database of video game release dates. The problem is, games sometimes don't get a specific release date. The release date might look like any of these:
2013
Spring 2013
April 21, 2013
What's the best way to setup my application to accommodate these different date types?

My first thought was to create a separate Date model and create a has_one belongs_to relationship with the Game model. Though, I'm not sure how that would affect my view implementation. I'd probably have to do some ajaxy magic thing that asked what kind of release date type to assign (year, season, or exact date) before it allowed input of the release date. And of course, it would have to be updateable for when the release date changes or gets more precise.

Adbot
ADBOT LOVES YOU

prom candy
Dec 16, 2005

Only I may dance
Simple idea would be to flag whether they're month specific and day specific. If something is 2013 you could just save it as 01-01-2013. Then you could use a little class or method to determine how to display it.

code:
class DateSpecificityFormatter
  def self.format(obj)
    if obj.released_on_specific_day?
      obj.released_on.strftime('%B %d %Y')
    elsif obj.released_on_specfic_month?
      obj.released_on.strftime('%B %Y')
    else
      obj.released_on.year.to_s
    end
  end
end
Something like that.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I too, would suggest a date field and a second field that describes the accuracy of the date. Then you could construct a method that puts the two together.

released_at: 1-1-2013
period: 'quarter'

looks like: Q1 2013

Or something like that. I'd imagine it's best to have a date column any way you decide to do it, just for sort order.

plasticbugs
Dec 13, 2006

Special Batman and Robin

Nolgthorn posted:

I too, would suggest a date field and a second field that describes the accuracy of the date. Then you could construct a method that puts the two together.

prom candy posted:

Simple idea would be to flag whether they're month specific and day specific. If something is 2013 you could just save it as 01-01-2013. Then you could use a little class or method to determine how to display it.

Thanks for the help. These suggestions worked. I'm going to have to be creative in my view to make selecting Q1..Q4 dates easy.

Daynab
Aug 5, 2008

I'm in love with this language. (Ruby, haven't started RoR yet though I'm nearly there.)
Everything is just so... smooth and understandable and I've never absorbed as much information in such a short time in my life before.
Maybe it's because this is the third language I learn the basics of and it's started clicking much faster, but regardless, this is awesome. :unsmith:

Also, the newly updated Codecademy course for it seems to be awesome. http://www.codecademy.com/tracks/ruby
I read through Learning Ruby The Hard Way (I had already read the python one) and then jumped into the second half of codecademy and it cleared up many things LRTHW had just kind of left in the air like symbols.

Daynab fucked around with this message at 11:10 on Jan 14, 2013

Physical
Sep 26, 2007

by T. Finninho
Here is a convenience I find lacking:
Ruby code:
MyModel.where( :some_criteria => my_var)
When my_var is nil, the SQL turns into "some_criteria = 0", but I don't want that, I want 'some_criteria is NULL' do I have to do it on my own or is there something I am missing?

Obsurveyor
Jan 10, 2003

Daynab posted:

Maybe it's because this is the third language I learn the basics of and it's started clicking much faster, but regardless, this is awesome. :unsmith:

Nope, ruby downright is an awesome language. You'll feel handcuffed and wonder why you have to do all this typing every time you have to go back to something else.

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.

Physical posted:

Here is a convenience I find lacking:
Ruby code:
MyModel.where( :some_criteria => my_var)
When my_var is nil, the SQL turns into "some_criteria = 0", but I don't want that, I want 'some_criteria is NULL' do I have to do it on my own or is there something I am missing?

what does `MyModel.where('some_criteria = ?', my_var)` do?

Pardot
Jul 25, 2001




Physical posted:

Here is a convenience I find lacking:
Ruby code:
MyModel.where( :some_criteria => my_var)
When my_var is nil, the SQL turns into "some_criteria = 0", but I don't want that, I want 'some_criteria is NULL' do I have to do it on my own or is there something I am missing?

I cannot reproduce this:

Ruby code:
>> my_var = nil
=> nil
>> Clip.where slug: my_var
  Clip Load (0.4ms)  SELECT "clips".* FROM "clips" WHERE "clips"."slug" IS NULL
=> []
>> my_var = 'abc'
=> "abc"
>> Clip.where slug: my_var
  Clip Load (2.7ms)  SELECT "clips".* FROM "clips" WHERE "clips"."slug" = 'abc'
=> []
Maybe it's due to the database you're using? I really don't know though.

MrDoDo
Jun 27, 2004

You better remember quick before we haul your sweet ass down to the precinct.

Physical posted:

Here is a convenience I find lacking:
Ruby code:
MyModel.where( :some_criteria => my_var)
When my_var is nil, the SQL turns into "some_criteria = 0", but I don't want that, I want 'some_criteria is NULL' do I have to do it on my own or is there something I am missing?

It seems like its how you are producing my_var. Is it being generated by some sort of count of query of its own that would return 0 instead of nil in the case of no results?

Physical
Sep 26, 2007

by T. Finninho
I'm using MySQL and my where clauses is changed to
Ruby code:
:criteria => 'NULL' 
and it is still substituting it with 0. The db column is a integer type.
Doing this
Ruby code:
where('criteria is NULL')
Get's the results I want, but then I have to build my own string before hand which is what I wanted to avoid.

e: It looks like it should work, I just have to examine what I have a little bit more. Thanks for confirming that it should work err'body.

ee: :cripes: Oh god it was because the value was being set to "", my numerous .nil? check's did nothing to prevent that, I am now using 'blank?'

Physical fucked around with this message at 20:42 on Jan 14, 2013

The Journey Fraternity
Nov 25, 2003



I found this on the ground!

Physical posted:

I'm using MySQL and my where clauses is changed to
Ruby code:
:criteria => 'NULL' 
and it is still substituting it with 0. The db column is a integer type.
Doing this
Ruby code:
where('criteria is NULL')
Get's the results I want, but then I have to build my own string before hand which is what I wanted to avoid.

e: It looks like it should work, I just have to examine what I have a little bit more. Thanks for confirming that it should work err'body.

ee: :cripes: Oh god it was because the value was being set to "", my numerous .nil? check's did nothing to prevent that, I am now using 'blank?'

We've all had that happen. Plus side is that it's a learning experience!

Physical
Sep 26, 2007

by T. Finninho
I still don't get what went wrong with
Ruby code:
:criteria => 'NULL' 
but maybe I just couldn't find it sifting through my console output for webrick since there is alot.

The Journey Fraternity
Nov 25, 2003



I found this on the ground!

Physical posted:

I still don't get what went wrong with
Ruby code:
:criteria => 'NULL' 
but maybe I just couldn't find it sifting through my console output for webrick since there is alot.

code:
irb(main):001:0> 'NULL'.to_i
=> 0

Physical
Sep 26, 2007

by T. Finninho
Good to know.

New question: I would like to create a sort of state-machine for my application. What I have is a form that can be in several different modes, the form has links on it to other items' edit forms that need to know what the current mode is from the base form.

A example of this is the authenticity_token and how the app is aware of what the current_user is without having to pass it around in the forms. How do I reproduce this?

e: looks like the session might be a means for this kind of functionality.

Physical fucked around with this message at 23:06 on Jan 14, 2013

Lexicon
Jul 29, 2003

I had a beer with Stephen Harper once and now I like him.
This should be super easy, but I can't quite work it out: I want to create a simple form in rails that's not coupled to an ActiveRecord model. I simply want to hit a controller, and then I'll deal with the posted params from there. However, when I click my button, nothing happens - my controller never gets hit. The route is properly set up.

Ruby code:
%form{:class => "form-inline", :action => "/blar", :method => "post"}
  %label
    From:
  %input{:type => "text", :placeholder => "yyyy-mm-dd", :class => "input-small datepicker"}
  %label
    To:
  %input{:type => "text", :placeholder => "yyyy-mm-dd", :class => "input-small datepicker"}
  %button{:type => "button", :class => "btn btn-primary"}
    Display

What am I missing here?

Physical
Sep 26, 2007

by T. Finninho

Lexicon posted:

This should be super easy, but I can't quite work it out: I want to create a simple form in rails that's not coupled to an ActiveRecord model. I simply want to hit a controller, and then I'll deal with the posted params from there. However, when I click my button, nothing happens - my controller never gets hit. The route is properly set up.

Ruby code:
%form{:class => "form-inline", :action => "/blar", :method => "post"}
  %label
    From:
  %input{:type => "text", :placeholder => "yyyy-mm-dd", :class => "input-small datepicker"}
  %label
    To:
  %input{:type => "text", :placeholder => "yyyy-mm-dd", :class => "input-small datepicker"}
  %button{:type => "button", :class => "btn btn-primary"}
    Display

What am I missing here?
Is it the difference between button and submit_tag? Or is your form tag crossing any div tags?

Lexicon
Jul 29, 2003

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

Physical posted:

Is it the difference between button and submit_tag? Or is your form tag crossing any div tags?

Just tried submit_tag - same result. And I'm not sure what you mean by the latter point. The HAML is well formed, I'm pretty sure.

Pardot
Jul 25, 2001




I'd guess that it is probably missing the CSRF tags. Use the form_tag helper.

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.

Here's a stupid question: can I use just an html snippet as a partial? I just want to stick a plain <script> underscore.js template into one of my views. It sucks in haml because I want nesting and stuff without breaking, and ERB breaks because they both use the <% %> delimiters.

e; meh, nevermind, I'm just going to use mustache delimiters instead. now do do a giant find/replace. I'm VIMming a little too hard today.

A MIRACLE fucked around with this message at 15:58 on Jan 15, 2013

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
You realize that you can put inline html inside haml, right? For example,

code:
#my
  .cool
    #haml
      .hierarchy
        <script type="text/template"><%= foo %></script>
http://chriseppstein.github.com/blog/2010/02/08/haml-sucks-for-content/

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.

Smol posted:

You realize that you can put inline html inside haml, right? For example,

code:
#my
  .cool
    #haml
      .hierarchy
        <script type="text/template"><%= foo %></script>
http://chriseppstein.github.com/blog/2010/02/08/haml-sucks-for-content/

yes but you still can't indent, correct?

Cocoa Crispies
Jul 20, 2001

Vehicular Manslaughter!

Pillbug

A MIRACLE posted:

yes but you still can't indent, correct?

You can if you put it in a haml :plain block, which doesn't escape:
code:
%p asdf
:plain
  <p>
    farts
  </p>
HTML code:
<p>asdf</p>
<p>
  farts
</p>

Physical
Sep 26, 2007

by T. Finninho
I'm not sure if I have seen this before but I feel like it exists. I want to create an object from a single link click using the built-in create/new routes. There is no need for a form, so I want to skip it.

Ruby code:
<%= link_to 'create an object', "/test_objects", :method => :put %>
<%= link_to 'create an object', "/test_objects", :method => :create %>
Something like that I think, or do I have to create my own route?
e: Got it, but how do I pass parameters along to it?
Ruby code:
<%= link_to 'create an object', {:controller => 'test_objects', :action => :create}, :method => :post  %>
ee: Whoa this is weird. I ran some migrations earlier and the MySQL Workbench isn't reflecting the new tables. How do I remedy this without rebuilding the database?
eee: :doh: Oh new branch from master means the default database.yml file, which connected to the VM's DB instead of the one running on my Host machine. That was bizarre to experience.

Physical fucked around with this message at 22:41 on Jan 16, 2013

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
a

DONT THREAD ON ME fucked around with this message at 03:17 on Oct 8, 2014

Physical
Sep 26, 2007

by T. Finninho

chumpchous posted:

I had this exact question earlier today. I didn't from inputs from the user, but I did want some parameters forwarded.

code:
<%= form_tag(:controller => "seasons", :action => 'create',:method => 'post',:params => {id: @series.id}) do %>	
	<%= submit_tag("Add a season") %>
<% end %>
I'm on week .5 of rails, so take this with a grain of salt -- only posting because I was struggling with this today.
You're pretty much right. Your params method didn't work for me. I'm still trying to figure out why the create request is handling as html instead of js/ajax response.

DankTamagachi
Jan 20, 2005
Tamagachi to your throat!
You guys might want to look into the :remote option on form tags- you can specify that it is an AJAX request via that flag.

http://www.alfajango.com/blog/rails-3-remote-links-and-forms/

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.

chumpchous posted:

I had this exact question earlier today. I didn't from inputs from the user, but I did want some parameters forwarded.

code:
<%= form_tag(:controller => "seasons", :action => 'create',:method => 'post',:params => {id: @series.id}) do %>	
	<%= submit_tag("Add a season") %>
<% end %>
I'm on week .5 of rails, so take this with a grain of salt -- only posting because I was struggling with this today.

It's customary to use the route helpers than to explicitly specify the controller/action/http method combination. For example, create_season_path is equivalent to your :controller => "seasons", :action => 'create',:method => 'post' definition.

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
a

DONT THREAD ON ME fucked around with this message at 03:17 on Oct 8, 2014

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
Yeah, I didn't think of the inflection issues at all.

Physical
Sep 26, 2007

by T. Finninho

chumpchous posted:

Yeah, this is something I was aware of, but couldn't make work at the time. I'm really liking rails, but dear god the emphasis on convention is frustrating when you're starting out. I generally gain a lot of understanding by looking at various examples and establishing a cause => effect relationship between things. In rails, the relationship is there, but it is rarely stated explicitly.
Same here. Drove me nuts but is getting way better. Reading this thread helped.

Smol posted:

For example, create_season_path is equivalent to your :controller => "seasons", :action => 'create',:method => 'post' definition.
I swear I tried the create_mything_path and it threw an exception. I'm glad I went through it though to learn how to do it without the helpers, allows for a better understanding of things going on. I was putting too much stuff in my form_tag at first, here are the two ways that I found to do it.

Ruby code:
  <%= form_for :my_model, :url=>{ :controller => :my_models, :action => :create}, :remote => true do |f| %>
    <%= submit_tag "x",  :class => "close", :remote => true %>
  <% end %>
  
  <%= form_tag(my_models_path, :remote => true, :action => :create) do %> 
    <%= submit_tag "x",  :class => "close", :remote => true %>
  <% end %>  
I think there is a redundancy in the first one by specifying the controller.

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
It's a good idea to run rake routes if you ever wonder what your real routes are. It lists all the shorthand methods for them as well (just add "_path" or "_url" to the end).

^^ You should be able to use just

code:
 <%= form_for(@my_model, :remote => true) do |f| %>
    <%= f.submit "x",  :class => "close" %>
  <% end %>  
form_for(@some_model) will create a form that is bound to either update or create action, depending on if your model is already saved to the database.

plasticbugs
Dec 13, 2006

Special Batman and Robin
I have a general Ruby question. But since we don't have a Ruby thread and I am working with data from a Rails app, I hope it's okay that this goes here:

I'm using Rubymotion, which lets you develop iOS apps in Ruby. I'm working with a locally hosted JSON resource, and a nifty gem called Bubblewrap, that wraps verbose iOS methods and makes them more Ruby-like. Anyway, here's my stumbling point. The Bubblewrap method to get and parse my JSON resource uses a callback block for when the request finishes.

code:
    BW::HTTP.get("http://0.0.0.0:3000/platforms/2/games.json") do |response|
      p BW::JSON.parse(response.body.to_str)
    end
# This prints an array of 30 objects
The callback ensures that the request is finished before it hands the response to the JSON parsing method.

The problem is, I don't know how to coerce the parsed JSON data (an array) into an instance variable. I can store the response, and work with it INSIDE the block, but I can't figure out how to get the parsed data outside of the block.

So this works:
code:
    BW::HTTP.get("http://0.0.0.0:3000/platforms/2/games.json") do |response|
      myvar = BW::JSON.parse(response.body.to_str)
      puts myvar  # This prints an array of objects to the console
    end
But this doesn't:
code:
    BW::HTTP.get("http://0.0.0.0:3000/platforms/2/games.json") do |response|
      @myvar = BW::JSON.parse(response.body.to_str)
    end

puts @myvar   # This prints nil
I also tried this:
code:
def my_method
    BW::HTTP.get("http://0.0.0.0:3000/platforms/2/games.json") do |response|
      BW::JSON.parse(response.body.to_str)
    end
end

@array = []

def my_other_method
    BW::HTTP.get("http://0.0.0.0:3000/platforms/2/games.json") do |response|
      @array << BW::JSON.parse(response.body.to_str)
    end
end

self.my_method #This method returns a Bubblewrap query
#object with an empty response because the block doesn't
#get a chance to run

self.my_other_method #This returns an empty array
Thanks in advance for any pointers.

Pardot
Jul 25, 2001




Block scoping in ruby isn't super intuitive. Try setting the variable before the block

Ruby code:
myvar = nil
BW::HTTP.get("http://0.0.0.0:3000/platforms/2/games.json") do |response|
      myvar = BW::JSON.parse(response.body.to_str)
      puts myvar  # This prints an array of objects to the console
end

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
That really doesn't help him, as the API is clearly asynchronous. That said, welcome to the wonderful world of asynchronous programming. Many things, like expecting to get useful return values from methods often don't exist in this world (especially in the node.js-esque callback hell side of things, which this API seems to be part of as well).

Civil Twilight
Apr 2, 2011

Take a look at the API Driven Example part of the RubyMotion tutorial, specifically "Color.find". It looks like they're accomplishing what you want to do by passing a block into the method that uses BubbleWrap, using block.call in the callback, and setting the instance variable in that block.

plasticbugs
Dec 13, 2006

Special Batman and Robin

Civil Twilight posted:

Take a look at the API Driven Example part of the RubyMotion tutorial, specifically "Color.find". It looks like they're accomplishing what you want to do by passing a block into the method that uses BubbleWrap, using block.call in the callback, and setting the instance variable in that block.

Smol posted:

That really doesn't help him, as the API is clearly asynchronous. That said, welcome to the wonderful world of asynchronous programming. Many things, like expecting to get useful return values from methods often don't exist in this world (especially in the node.js-esque callback hell side of things, which this API seems to be part of as well).

The asynchronous nature of it is what's tripping me up for sure. This was a big help. I'm not familiar at all with this design pattern (or any design pattern), but after staring at the code for an hour, I was able to pass the response data into an object. Now I just have to maneuver those objects into my TableView and life will be good.

Smol
Jun 1, 2011

Stat rosa pristina nomine, nomina nuda tenemus.
Yep, event-driven programming can be quite complex. That said, it's a shame the Rubymotion devs didn't choose to use Fibers, using them can really help make event-driven programming more manageable.

DONT THREAD ON ME
Oct 1, 2002

by Nyc_Tattoo
Floss Finder
Warning: This ended up being a really stupid problem.

Okay, I'm confused.

I have a 3 model hierarchy, Series -> Seasons -> Episodes.

code:

# == Schema Information
#
# Table name: series
#
#  id         :integer          not null, primary key
#  title      :string(255)
#  initials   :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Series < ActiveRecord::Base
  attr_accessible :initials, :title
  has_many :seasons, :dependent => :destroy
  has_many :episodes, :through => :seasons
  validates :initials, :title, :uniqueness => true
  validates :initials, :length => { maximum: 2, minimum: 2 }
  validates :title, :length => { minimum: 1, maximum: 50 }
end
# == Schema Information
#
# Table name: seasons
#
#  id            :integer          not null, primary key
#  series_id     :integer
#  season_number :integer
#  created_at    :datetime         not null
#  updated_at    :datetime         not null
#

class Season < ActiveRecord::Base
  attr_accessible :season_number
  belongs_to :series
  has_many :episodes, :dependent => :destroy

  validates :series_id, :presence => true
  validates :season_number, :uniqueness => { :scope => :series_id }, :length => { maximum: 2 }, numericality: true

end

# == Schema Information
#
# Table name: episodes
#
#  id             :integer          not null, primary key
#  season_id      :integer
#  title          :string(255)
#  created_at     :datetime         not null
#  updated_at     :datetime         not null
#  episode_number :integer
#

class Episode < ActiveRecord::Base
  attr_accessible :title, :episode_number
  belongs_to :season, :include => :series
  validates :title, :episode_number, :presence => true
  validates :title, :length => { :maximum => 150 }
  validates :episode_number, numericality: {only_integer: true}
  validates :episode_number, :uniqueness => {:scope => :season_id }

  default_scope order: 'episodes.episode_number ASC'
end
This has been working fine. I create Series with Series.create, Seasons with @series.seasons.create, and Episodes with @seasons.episodes.create.

I've spent the day messing around with my controllers and routes (I nested the route on these 3 models, just to get an idea of how it works). I'm struggling a bit with rerouting everything, but that's fine. What I'm really confused about is that now, I can no longer create new seasons. They tell me I need to define a series_id.

code:
1.9.3-p362 :001 > s = Series.create(title:"foo",initials:"FB")
1.9.3-p362 :007 > s.seasons.create!(season_number:1)
   (0.1ms)  begin transaction
  Season Exists (0.1ms)  SELECT 1 AS one FROM "seasons" WHERE ("seasons"."season_number" = 1 AND "seasons"."series_id" IS NULL) LIMIT 1
   (0.0ms)  rollback transaction
ActiveRecord::RecordInvalid: Validation failed: Series can't be blank

(I believe the Season Exists error is because the season_id is nil, not because the season_number exists).

Of course, I can't mass assigned the series_id, (and I don't want to). I've changed absolutely nothing on the models, aside from adding the default_scope order to Episodes. As I said, I've changed a lot with my controllers and routes, but none of that should apply to direct calls from within the console, right? What am I missing?

edit: I figured it out. I had a helper function in my Series model,

code:
def season
	Season.where("series_id = ?", id)
end
I left it out of my excepts above because I thought it wasn't actually doing anything. It was there from before I understood what I was doing. I was right: it wasn't doing anything. However, I'd inadvertently changed that code to:
code:
def seasons
Which, of course, conflicts with the implicit definitions of Series.seasons from the has_many declaration. Ooops.

DONT THREAD ON ME fucked around with this message at 04:23 on Jan 21, 2013

Adbot
ADBOT LOVES YOU

plasticbugs
Dec 13, 2006

Special Batman and Robin

Smol posted:

Yep, event-driven programming can be quite complex. That said, it's a shame the Rubymotion devs didn't choose to use Fibers, using them can really help make event-driven programming more manageable.

Funnily enough, Apple seems to have solved some of these asynchronus issues with Grand Central Dispatch. After a little bit of reading, I figured out how to get data out of my JSON objects and into Ruby objects. If anyone is interested, there's a project on github here which was a huge help.

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