Search Amazon.com:
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 $3,400 per month for bandwidth bills alone, and since we don't believe in shoving popup ads to our registered users, we try to make the money back through forum registrations.
«141 »
  • Post
  • Reply
wunderbread384
Jun 24, 2004
America's favorite bread

skidooer posted:

I'm not convinced it's better, but I do like some of the aspects of it. Thoughts?

I can definitely see where it would be helpful if you have a different group of people creating the application logic and the actual page design. Right now the view is where they sort of collide, but by separating views and templates out even further this way you can keep them at least a little bit more separated.

On the other hand if your designers are like mine, they just tell you what it should look like and you code the whole thing. I think if this is the case it's taking separation of logic and design a little bit too far. Basically too much complication for not enough gain.

Adbot
ADBOT LOVES YOU

jonnii
Dec 28, 2002
god dances in the face of the jews

skidooer posted:

find(:all, :joins => 'INNER JOIN bar ON bar.foo_id = foo.id')

You can do this with named associations like :include now (if you use edge).

find(:all, :joins => :bar)

Hop Pocket
Sep 22, 2003



Is there a way to disable SQL logging for some statements within Rails? I have an images table that I'm uploading somewhat large files to, and the SQL logging is causing all sorts of Terminal.app problems. I don't want to disable SQL logging completely in the development environment, but I would like to be able to not have it log those statement that are doing INSERTs into the images table.

The Journey Fraternity
Nov 25, 2003




Hop Pocket posted:

Is there a way to disable SQL logging for some statements within Rails? I have an images table that I'm uploading somewhat large files to, and the SQL logging is causing all sorts of Terminal.app problems. I don't want to disable SQL logging completely in the development environment, but I would like to be able to not have it log those statement that are doing INSERTs into the images table.

If you're putting them in their own column, I suppose you could use filter_parameter_logging, but that might not completely fit your needs. This might also cause problems if you have columns similarly-named to your image data column elsewhere in your models.

The Journey Fraternity fucked around with this message at Nov 29, 2007 around 06:09

poemdexter
Feb 18, 2005

Hooray Indie Games!


I'm writing a little networking site and I can't figure out how to get anything into a table without using a form.

Forms are great when registering users or creating groups, but I want the group table to have a 'creator' attribute that holds the user id from a session. I know how to get the id from the session, but have no idea how to get it inside the table upon creation.

Here is the code from my new.rhtml from the group view (REST is awesome)
code:
<% form_for :group, :url => groups_url, :html => { :method => :post } do |f| -%>
  <p>Title:<br /><%= f.text_field :title, :size => 60 %></p>
  <p>Body:<br /><%= f.text_area :info, :rows => 20, :cols => 60 %></p>
  <p>News:<br /><%= f.text_area :news, :rows => 20, :cols => 60 %></p>
  <p>Website:<br /><%= f.text_field :website, :size => 60 %></p>
  <p>Email:<br /><%= f.text_field :email, :size => 60 %></p>
  <%= submit_tag 'Save' %> or <%= link_to 'cancel', groups_url %>
<% end -%>
Am I supposed to slap some sort of :creator => logged_in_user.id somewhere?

zigb
Mar 21, 2007


poemdexter posted:

I'm writing a little networking site and I can't figure out how to get anything into a table without using a form.
...
Here is the code from my new.rhtml from the group view (REST is awesome)
...
Am I supposed to slap some sort of :creator => logged_in_user.id somewhere?

It makes the most sense to me to put that in your controller instead. So something like:
code:
def new
	@newGroup = Group.new
	@newGroup.attributes= params[:group]
	@newGroup.creator = logged_in_user.id
	@newGroup.save
end
Of course if you use update_attributes instead of attributes=, you'll want to add the creator first.

MonkeyMaker
May 22, 2006

What's your poison, sir?

zigb posted:

It makes the most sense to me to put that in your controller instead. So something like:
code:
def new
	@newGroup = Group.new
	@newGroup.attributes= params[:group]
	@newGroup.creator = logged_in_user.id
	@newGroup.save
end
Of course if you use update_attributes instead of attributes=, you'll want to add the creator first.

@newGroup = Group.new(params[:group]) would save a line. Not that it really matters, I guess.

Anyone know of a quick/easy way to provide 'validates_X'-style validation on non-model checks? Like if a .find comes up blank, show an error/alert, instead of having to code that exception explicitly every time?

skidooer
Aug 5, 2001


poemdexter posted:

I want the group table to have a 'creator' attribute that holds the user id from a session.
code:
class GroupsController < ApplicationController
  def create
    @group = current_user.groups.build(params[:group])    
    redirect_to groups_url if @group.save
  end
  
  private
    def current_user
      @current_user ||= User.find(session[:user_id])
    end
end

MonkeyMaker posted:

Anyone know of a quick/easy way to provide 'validates_X'-style validation on non-model checks? Like if a .find comes up blank, show an error/alert, instead of having to code that exception explicitly every time?
I guess you could do something along the lines of the following. I don't find it all that appealing, personally.
code:
class GroupsController < ApplicationController
  def index
    @groups = Group.find(:all)  
    validates_presence_of @groups
  end
  
  private
    def validates_presence_of(collection)
      # Handle the failure however you see fit
      raise ActiveRecord::RecordNotFound if collection.blank?
    end
end

skidooer fucked around with this message at Dec 4, 2007 around 08:04

poemdexter
Feb 18, 2005

Hooray Indie Games!


MonkeyMaker posted:

@newGroup = Group.new(params[:group]) would save a line. Not that it really matters, I guess.

code:
  def create
  	@group = Group.new(params[:group])
  	@group.creator = logged_in_user.id
  	@group.save
This was the simplest way to go about it. Thanks. I have no idea what everyone else's code does, but I'm still new to both Ruby and the Rails gem.

Pardot
Jul 25, 2001



poemdexter posted:

I'm still new to both Ruby and the Rails gem.

I would really recommend using edge rails over gem rails. You get to take advantage of all of the new improvements and such. And rails 2 is due out soon anyway.

My favorite way to do it is to check the trunk out into your own repo using piston. It's a lot nicer than svn externals.

Land Mime
Jul 13, 2007
Love never blows up and gets killed

I've got an ActiveRecord question. Say I have a site for people to say which movies they liked certain actors in. So there are three tables

user(id, login)
movies(id, title)
actors(id, name)

The relationships are
A User can see many movies
A User can like many actors in a particular movie

Which makes the join tables something like
users_movies(user_id, movie_id)
user_movie_actors(user_id, movie_id, actor_id)

I can't figure out how to correctly describe this in ActiveRecord. I think the result should be a User object that contains a list of Movies they've seen, which contains the Actors they liked in that movie. Does anyone know how to describe this to ActiveRecord? I can't figure out how to have a (user, movie) pair have a many to many relationship with actors.

jonnii
Dec 28, 2002
god dances in the face of the jews

I would do it like this

code:

class Movies < ARB
   has_many :actors, :through => :roles
   has_many :roles
end

class Role < ARB
   belongs_to :movie
   belongs_to :actor
end

class Favourite < ARB
   belongs_to :user
   belongs_to :role
end

class User < ARB
   has_many :favourites
   has_many :roles, :through => :favourites
end

I'm sure you get the idea...

skidooer
Aug 5, 2001


poemdexter posted:

This was the simplest way to go about it. Thanks. I have no idea what everyone else's code does, but I'm still new to both Ruby and the Rails gem.
I would still recommend going with the association proxy. It's the Rails way.

Based on the information you have given, I'm assuming your models look something like this:
code:
class User < ActiveRecord::Base
  has_many :groups, :foreign_key => :creator
end

class Group < ActiveRecord::Base
  belongs_to :user, :foreign_key => :creator
end
Now, in your controller you'd write something like:
code:
@group = logged_in_user.groups.build(params[:group])
which will give you the same result as this:
code:
@group = Group.new(params[:group])
@group.creator = logged_in_user.id
without putting database specific details (i.e. the id method) into your controller.

poemdexter
Feb 18, 2005

Hooray Indie Games!


problem solved.

poemdexter fucked around with this message at Dec 5, 2007 around 00:25

Lamont Cranston
Sep 1, 2006

how do i shot foam


OK, I'm trying to wrap my brain around this RESTful stuff, and I think I've got it. I was experimenting with refactoring one of my existing apps to REST, but here's the snag I run into.

For my "user" controller, I have my routes set up like so:
code:
map.connect 'user/:user', :controller => "user", :action => "view"
So I can have URIs like "foobar.com/user/Lamont_Cranston" instead of "foobar.com/user/14525". I can't figure out how to do this in REST with map.resource. I know I could override to_param in my model but I wouldn't like to use :id for anything but the id. Anybody know how I could accomplish this?

poemdexter
Feb 18, 2005

Hooray Indie Games!


what could be the reason for when I try to update a friendship, I get redirects after completion going to:

http://localhost:3000/users/2/friends?friend_id=1

with this code in the update method:
code:
redirect_to friends_path(:user_id => logged_in_user)
However, when creating the friendship the first time I get redirects going to:

http://localhost:3000/users/2/friends

with this code in the create method:
code:
redirect_to friends_path(:user_id => logged_in_user)
Why am I getting funky redirects when I just want to go to the same place?

skidooer
Aug 5, 2001


Lamont Cranston posted:

I can't figure out how to do this in REST with map.resource.
:id doesn't necessarily have to be the ID of the record. You can do something like this:
code:
map.resources :users

def show
  @user = User.find_by_permalink(params[:id]) || User.find(params[:id])
end

<%= link_to h(user.name), user_path(user.permalink) %>
If you're dead set on using :user instead of :id, just define an additional route.
code:
map.resources :users
map.named_user 'user/:user', :controller => 'users', :action => 'show'

<%= link_to h(user.name), named_user_path(user.permalink) %>

Al Azif
Nov 1, 2006


What's the usual way of setting a page's title? All my pages use the same layout, I'm assuming I should put something like this in my layout:

code:
<head>
  <title><%= @title %></title>
</head>
but should I set @title in each controller or each view?

Trabisnikof
Dec 24, 2005
элита хакера

Al Azif posted:

What's the usual way of setting a page's title? All my pages use the same layout, I'm assuming I should put something like this in my layout:

code:
<head>
  <title><%= @title %></title>
</head>
but should I set @title in each controller or each view?

I do it in the view. Sure I may be just going <% @title = "You own " + @dog.name + "!" %>. But that's one less thing to have to make sure I do if I do screwy things with renders.

Hop Pocket
Sep 22, 2003



You can also use content_for to supply extra information to your layout.

application.rhtml

code:
....
<head>
  <title><%= yield :title %></title>
</head>
....
view.rhtml

code:
<% content_for(:title) do %>
I am a title, short and stout
<% end %>

SeventySeven
Jan 18, 2005
I AM A FAGGOT WHO BEGGED EXTREMITY TO CREATE AM ACCOUNT FOR ME. PLEASE PELT ME WITH ASSORTED GOODS.

What would be the sanest way to add a "global" variable accessible by all controllers/views in an app? At the moment I've just got a method in the application helper that returns the variable but I was wondering if there was a more "rails" way to do this.

skidooer
Aug 5, 2001


Hop Pocket posted:

You can also use content_for to supply extra information to your layout.
I like this method. Except I'd add a helper method for setting the title so that the templates aren't so cluttered with huge content_for blocks.

Something like:
code:
def title(title)
  content_for(:title) { title }
end

SeventySeven posted:

What would be the sanest way to add a "global" variable accessible by all controllers/views in an app?
Global as in a constant, or something you want to set on each load, like so?
code:
class ApplicationController < ActionController::Base
  before_filter :set_some_variable

  private
    def set_some_variable
      @variable_accessible_to_controllers_and_views = Model.find(:first)
    end
end

skidooer fucked around with this message at Dec 5, 2007 around 16:37

SeventySeven
Jan 18, 2005
I AM A FAGGOT WHO BEGGED EXTREMITY TO CREATE AM ACCOUNT FOR ME. PLEASE PELT ME WITH ASSORTED GOODS.

Just a constant, nothing fancy.

Lamont Cranston
Sep 1, 2006

how do i shot foam


SeventySeven posted:

Just a constant, nothing fancy.

I used environment.rb to store a constant with my Google API key, that might work for you.

Nolgthorn
Jan 29, 2001



MonkeyMaker posted:

Anyone know of a quick/easy way to provide 'validates_X'-style validation on non-model checks? Like if a .find comes up blank, show an error/alert, instead of having to code that exception explicitly every time?

If you use .find_by_id in place of .find, then if that .find_by_id comes up blank it will return nil instead of an error.
code:
unless @group = Group.find_by_id(params[:id])
  redirect_to home_url
  return false
end
# Do something with @group here.
I use the above code all the time because this, below, would page the database twice.
code:
unless Group.exists?(params[:id])
  redirect_to home_url
  return false
end
@group = Group.find(params[:id])
# Do something with @group here.

Nolgthorn fucked around with this message at Dec 6, 2007 around 02:50

atastypie
Dec 2, 2000



Nolgthorn posted:

If you use .find_by_id in place of .find, then if that .find_by_id comes up blank it will return nil instead of an error.

This thread is so great for little tidbits like this. Thanks

GroceryBagHead
Nov 28, 2000



I found this very useful when you need to sandwich a custom method that should be called when calling existing Rails method yet being able to still use it later on... Sorry, this sounds confusing...

Read this: alias_method_bling http://errtheblog.com/post/1109

Snowmanatee
Jun 6, 2003

Stereoscopic Suffocation!

Does anyone have a copy of Agile Web Development with Rails that they might want to sell?

Nolgthorn
Jan 29, 2001



I'm trying to write sort of a short-and-sweet authentication permissions system. As it is right now, I know how I think I want it to work but I'm having trouble making it escape the controller action that was running if validation fails.

Controller in some action:
code:
      if belongs_to_current_user?(@article)
        # User must have permission to edit their own article
        permission_required("article", "edit")
      else
        # User must have permission to edit other's articles
        permission_required("article", "edit-a")
      end
Application controller:
code:
  # Denies access to unauthorized users.
  def permission_required(cont, code)
    unless permission?(cont, code)
      flash[:warning] = "You don't have the permission required for access to this function"
      redirect_to home_url
      return false
    end
  end
The "return false" I have there, I want it cancel processing from the action in my controller but it only cancels processing from the rest of the permission_required method.

I'm at a loss as to how to put code safely after calling permission_required in my controller, without worrying about it getting executed anyway after the user is redirected.

skidooer
Aug 5, 2001


Nolgthorn posted:

I'm at a loss as to how to put code safely after calling permission_required in my controller, without worrying about it getting executed anyway after the user is redirected.
If you're dead set on that API, you could raise a permission denied exception in your permission_required function and rescue it outside of the controller method. Although I'm wondering about how clear it will be to anyone else who may be working on your code in the future, although I guess it's no worse than the magic that happens when ActiveRecord::RecordNotFound is raised.
code:
class ActionController::Base
  class PermissionDenied < ActionControllerError; end
  
  def perform_action_with_permission_exceptions
    perform_action_without_permission_exceptions
  rescue PermissionDenied
  end
  
  alias_method_chain :perform_action, :permission_exceptions
end

skidooer fucked around with this message at Dec 6, 2007 around 18:47

SeventySeven
Jan 18, 2005
I AM A FAGGOT WHO BEGGED EXTREMITY TO CREATE AM ACCOUNT FOR ME. PLEASE PELT ME WITH ASSORTED GOODS.

Can anyone tell me why this WON'T loving INCREMENT?

code:
    @item = OrderItem.find_by_access_key(@id)
    if @item == nil
      redirect
      return
    end
    
    @item.increment!(@item.collected)
collected is an int field in the order_item table defaulting to 0 (though I've manually set it to other values with no success). @item is a valid object.

Hammertime
May 21, 2003
stop

SeventySeven posted:

Can anyone tell me why this WON'T loving INCREMENT?


collected is an int field in the order_item table defaulting to 0 (though I've manually set it to other values with no success). @item is a valid object.

Based on the API source, I believe it's expecting the name(or maybe the symbol) of the attribute.

Try: @item.increment!('collected')

SeventySeven
Jan 18, 2005
I AM A FAGGOT WHO BEGGED EXTREMITY TO CREATE AM ACCOUNT FOR ME. PLEASE PELT ME WITH ASSORTED GOODS.

Hammertime posted:

Based on the API source, I believe it's expecting the name(or maybe the symbol) of the attribute.

Try: @item.increment!('collected')

Motherfucker. Thanks a lot.

Sharrow
Aug 20, 2007

 
Dave? Say hello to Sid for me.


code:
Changeset 8328

Timestamp:  12/07/07 04:34:12 (6 hours ago)
Author:     david

Message:    Tagged Rails 2.0.0

Files:      tags/rel_2-0-0 (copied from trunk)
I imagine the official announcement will be out later after all the gem servers have updated.

HIERARCHY OF WEEDZ
Aug 1, 2005



Sharrow posted:

code:
Changeset 8328

Timestamp:  12/07/07 04:34:12 (6 hours ago)
Author:     david

Message:    Tagged Rails 2.0.0

Files:      tags/rel_2-0-0 (copied from trunk)
I imagine the official announcement will be out later after all the gem servers have updated.

God, I cannot wait to start playing around with Rails 2.0. I just have to make it through finals week first This blog post from the Ruby on Rails blog shows a lot of the work that's been pushed into the newest release, and it all sounds really exciting.

jonnii
Dec 28, 2002
god dances in the face of the jews

Seems like they found a last minute blocker.

It's going to be 2.0.1.

Nolgthorn
Jan 29, 2001



shopvac4christ posted:

This blog post

This looks neat. I like this part, it may help with my problem.

quote:

Action Pack: Exception handling

Lots of common exceptions would do better to be rescued at a shared level rather than per action. This has always been possible by overwriting rescue_action_in_public, but then you had to roll out your own case statement and call super. Bah. So now we have a class level macro called rescue_from, which you can use to declaratively point certain exceptions to a given action. Example:


class PostsController < ApplicationController
rescue_from User::NotAuthorized, :with => :deny_access

protected
def deny_access
...
end
end

I like to keep things as tidy as possible.

rolocroz
May 21, 2004

Do me a favor. Say a prayer!

What's the best way to get Ruby installed on Windows XP? Last time, I tried the one-click installer, but that installed a bunch of crap I don't want and couldn't unselect (some IDE, if I recall correctly, and some other stuff that was hard to remove). I tried just downloading the plain Ruby 1.8.6 binary from ruby-lang.org, which seemed promising, but it turns out that that's missing lots of DLLs that are required by RubyGems and other such things. Do I have to use the one-click installer, or is there a better option?

savetheclocktower
Sep 23, 2004

You wait and see, Mr. Caruthers. I will be president! I'll be the most powerful president in the history of America. And I'm gonna clean up this country!

rolocroz posted:

What's the best way to get Ruby installed on Windows XP? Last time, I tried the one-click installer, but that installed a bunch of crap I don't want and couldn't unselect (some IDE, if I recall correctly, and some other stuff that was hard to remove). I tried just downloading the plain Ruby 1.8.6 binary from ruby-lang.org, which seemed promising, but it turns out that that's missing lots of DLLs that are required by RubyGems and other such things. Do I have to use the one-click installer, or is there a better option?

You couldn't unselect ScITE? That's the only unnecessary thing it installs, if I recall correctly, and you can opt out of it.

Adbot
ADBOT LOVES YOU

atastypie
Dec 2, 2000



I was about to say InstantRails, but I went to it's website and apparently it has been replaced by BitNami.

Has anyone here done batch/multiple file upload within a rails application before?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply
«141 »