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
skidooer
Aug 6, 2001

zigb posted:

Documentation. For gently caress's sake people, at least pretend like you're trying.
I suppose it might be a little daunting for the first time user. Honestly, I prefer to just read the source code anyway. Why bother with someone's english interpretation when you've got perfectly good source code to go by?

quote:

Server restarts. Our dev server is also, unfortunately, a production server for different apps in other languages. (don't blame me, I didn't do it :().
Is there any reason why you aren't developing on your local system? That is the Rails way.

quote:

Added/Edited something in the /lib path? Restart Apache. This makes any sort of iterative development of libs/mixins a huge pain in the rear end.
Unless you were using an ancient version of Rails, or running in production mode, that isn't true.

quote:

SQL Logging. Didn't work, even when I triple checked that the /tmp and /log dirs had proper permissions and that logging wasn't disabled in the environment files.
SQL logging doesn't happen in production unless you increase the log level. I've never seen it not work in development mode.

quote:

Not that I mind writing SQL, but I prefer to write it in one large understandable chunk instead of splitting it up into mini-clauses, like :conditions => "[some sql]", :order => "[some sql]", etc.
They're split up so things like scopes can be applied. I suppose AR could implement an SQL parser so that you can write whole SQL statements, but that seems like a lot of effort for little benefit.

Although it's rare that I find myself writing any SQL at all. I'll assume it's your use of a schema that wasn't designed for ActiveRecord that you had to write a lot of SQL to work around those limitations.

quote:

Most find queries that required a JOIN or two had to be written using find_by_sql.
find(:all, :joins => 'INNER JOIN bar ON bar.foo_id = foo.id')

quote:

Controller initialize function. It causes "Internal Server Error" when I put simple logic in there. Example (this kills rails): "if null != params[:a_param]; end". Same thing when I put the logic in question into a method and call it from initialize. No problems when I call that same method from one of the actions instead.
params is your problem here. It's nil. There is no [] method defined for NilClass. If you're doing what I think you are, you want to use a before_filter instead.

quote:

Different expectations for overriding ActionController::initialize and ActiveRecord::initialize.
The odds that you'd ever want to overwrite initialize in either class are extremely low. I can't think of any reason why you'd ever want to, really.

quote:

While the above issues were all annoyances, the need to restart Apache after making code, not configuration, changes is the kicker.
Run your application as a CGI process and it will work just as you desire. But I'm sure you'd rather have the performance benefits of not reloading your code every time in production.

skidooer fucked around with this message at 17:50 on Nov 20, 2007

Adbot
ADBOT LOVES YOU

Hop Pocket
Sep 23, 2003

Having had to unfortunately work with FastCGI instead of Mongrel recently, I can understand your pain. But yeah, try to look into using Mongrel instead.

LOLLERZ
Dec 9, 2003
ASK ME ABOUT SPAMMING THE REPORT FORUM TO PROTECT ~MY WIFE'S~ OKCUPID PERSONALS ANALYSIS SA-MART THREAD. DO IT. ALL THE TIME. CONSTANTLY. IF SHE DOESN'T HAVE THE THREAD, SHE'LL WANT TO TALK TO ME!

skidooer posted:

Why bother with someone's english interpretation when you've got perfectly good source code to go by?
This is such an incredibly bad mentality about documentation, I don't even know where to start.

spacepirate
Feb 7, 2005
Yarr mateys!
I have been solving an unusual problem with rails, so far with very little trouble at work. Part of the product we ship people is a web interface that runs off a single executable and does not deploy to IIS or apache. The other kicker is that it has to dynamically support sqlite, sql server, oracle and soon mysql by reading the registry.

I am still in the early stages of development but have been amazed at how easy it has been to accomplish this stuff.

My question is thus, in the other parts of our product we make "smart" update statements. So if you edit a user you pass the changed user and the original user and then you get an update statement that only updates changed fields. Is there a mechanism for this in activerecord? Do I have to make my own?

wunderbread384
Jun 24, 2004
America's favorite bread

skidooer posted:

I suppose it might be a little daunting for the first time user. Honestly, I prefer to just read the source code anyway. Why bother with someone's english interpretation when you've got perfectly good source code to go by?

Why read source code when you have a perfectly good English explanation to go by?

Of course in Rails you almost never do, but that's just a weakness of Rails more than anything else.

skidooer
Aug 6, 2001

wunderbread384 posted:

Why read source code when you have a perfectly good English explanation to go by?
I find the code much easier to read and understand. I almost always ignore the documentation and dive right into the code. I guess I'm just weird. :unsmith: I will resort to the documentation if the code is poorly written, but I wouldn't lump Rails into that category.

skidooer fucked around with this message at 20:08 on Nov 20, 2007

spacepirate
Feb 7, 2005
Yarr mateys!
code:
def save
    create_or_update
end
Fantastic, self explaining code right there, especially since create_or_update is not listed in the Rails API.

Hop Pocket
Sep 23, 2003

For those of you using Mongrel in a deployment environment, how many Mongrel processes do you start? I know that it's all dependent on the application, load, # of static pages, etc. I'm setting up some hosting with Joyent, and you have to request Mongrel ports for a shared hosting environment, so I was just curious.

hmm yes
Dec 2, 2000
College Slice

spacepirate posted:

Fantastic, self explaining code right there, especially since create_or_update is not listed in the Rails API.

Yeah, that isn't exactly ideal, but it's not like this should be a problem. Your first reaction when you see something like that is:

1) search/grep for 'def create_or_update' if you're reading the source in a text editor

or

2) google 'rails create_or_update'

Both of those will net you the answer within 10 seconds, and the code is simple enough that you should know what's going on as soon as you finish reading it. No need for extra documentation there :S

code:
# File active_record/base.rb, line 2021
def create_or_update
  raise ReadOnlyRecord if readonly?
  result = new_record? ? create : update
  result != false
end

hmm yes fucked around with this message at 20:58 on Nov 20, 2007

skidooer
Aug 6, 2001

spacepirate posted:

Fantastic, self explaining code right there, especially since create_or_update is not listed in the Rails API.
From that snippet I know that saving the object will create a new database record or update an existing record if one already exists. What more can be said about it?

Evil Trout
Nov 16, 2004

The evilest trout of them all

Hop Pocket posted:

For those of you using Mongrel in a deployment environment, how many Mongrel processes do you start? I know that it's all dependent on the application, load, # of static pages, etc. I'm setting up some hosting with Joyent, and you have to request Mongrel ports for a shared hosting environment, so I was just curious.

My site, Forumwarz runs on 10 Mongrels behind an nginx proxy. It's pretty snappy, each Mongrel process seems to be using about 50-60M of RAM on a 2.4Ghz Core2Duo dedicated server.

zigb
Mar 21, 2007
First off, I want to say that I really appreciate people taking the time to try to address some of the issues I had mentioned with our rails setup. When I hit the post button late last night I was expecting to be flamed out of hand. Maybe I'll have to spend more time in the COBOL cavern and try to help out where possible.

I'll address skidooer's responses because he was very thorough and his responses captured the gist what everybody seems to be saying:

skidooer posted:

Is there any reason why you aren't developing on your local system? That is the Rails way.


I would have preferred that. I work on a machine that is managed by our IT staff, who are extremely paranoid and won't install anything resembling a server, even if I can lock it down to local access only. To put things in perspective, I had to get permission from my supervisor and dept. head before they would install WinMerge. Basically, local dev is out.

anal wink posted:

Is there a reason you're not using mongrel?

wunderbread384 posted:

...why are you running FastCGI for your development server?

It's not my server, I have no choice. In fact, I barely have a user account. I'm grateful for the comments people left re: FastCGI because if I can eliminate the Apache restarts (well, make the case to the server admin and hopefully get a change) I'd be a much happier camper.

In order to help resolve my ignorance on the matter, can I run Mongrel behind Apache? The decision has been made that Apache WILL be our http server, so any solutions I come up with need to be Apache-centric.

skidooer posted:

Unless you were using an ancient version of Rails, or running in production mode, that isn't true.


Rails 1.2.3 on Ruby 1.8.5. We're currently supporting another RoR app written by a different dev on this same box, so neither of those are subject to change. Also, I'm running in development mode.

skidooer posted:

[re: SQL Logging]I've never seen it not work in development mode.

I hate always being the exception to the rule! :(

skidooer posted:

I'll assume it's your use of a schema that wasn't designed for ActiveRecord that you had to write a lot of SQL to work around those limitations.

skidooer posted:

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

Likely too true. I'll have to try that :joins thing, btw, I was totally unaware it existed ;)..

grob posted:

-- what kind of joins are you doing that aren't handled elegantly by ActiveRecord?


Don't say you didn't ask for it :) ... This is for a reports type section of the site. The nastiness of this has much to do with the enforced crappy DB schema. Here's as brief an explanation as I can muster.. Payments belong to Schools and Costs. Costs belong to DatabaseInformations, which are really what this app is tracking. I need a list of all payments within a date range, for a few specific Schools. The date range is determined by Cost.subscriptionStart and Cost.subscriptionEnd. I need to order these Payments for display by the Payment.school.schoolName, then Payment.school.library, then Payment.cost.databaseInformation.databaseName. Final note: this report gets run perhaps twice in a blue moon, so the inefficient SQL doesn't make me too nervous.

@skidooer - I guess I just proved your point about reading English where the code might be more straightforward. I can only plead my desire to very briefly explain the query below without getting too far into specifics.
code:
sql = "SELECT p.* FROM payment AS p \
	LEFT JOIN school AS s ON p.schoolID = s.schoolID \
	LEFT JOIN cost AS c ON p.costID = c.costID \
	LEFT JOIN databaseInformation AS d on c.databaseID = d.databaseID
	WHERE s.schoolName LIKE '%school redacted%' && library NOT LIKE '%library also redacted%' \
	&& c.subscriptionStart >= '" + @dateStart.to_formatted_s(:db) + "' \
	&& c.subscriptionEnd <= '" + @dateEnd.to_formatted_s(:db) + "' \
	ORDER BY s.schoolName, s.library, d.databaseName"
					
@payments = Payment.find_by_sql(sql)
If there's some way AR would make this statement go away, I want to know about it!

skidooer posted:

params is your problem here. It's nil. There is no [] method defined for NilClass. If you're doing what I think you are, you want to use a before_filter instead.

skidooer posted:

The odds that you'd ever want to overwrite initialize in either class are extremely low. I can't think of any reason why you'd ever want to, really.

Taking your second statement first, is a controller's initialize method not the best place to put code that I want executed for each action? It seems DRYer than making a separate method and calling that from each action. I also think we've got a slight terminology mismatch here. Anytime I define a function that's already been defined in a base class I'm overriding it, whether I call super() from it or not. Of course if I call super() at the start of my newly declared method I'm really just modifying the existing functionality instead of providing entirely new functionality.

You're saying that params is unavailable/nil in a controller's initialize method? Any specific reason why? If not this is still good to know. My code that it barfed on was something like "if nil != params[:date_from] && nil != params[:date_to]". I was basically setting up some default vars for the actions if those parameters had been provided.

Again, thanks everybody for the constructive comments, I'll be looking forward to lending a hand where I'm qualified to in this forum.

zigb fucked around with this message at 22:47 on Nov 20, 2007

wunderbread384
Jun 24, 2004
America's favorite bread

zigb posted:

Taking your second statement first, is a controller's initialize method not the best place to put code that I want executed for each action? It seems DRYer than making a separate method and calling that from each action.

Sucks about your development environment, that's ridiculous.

Anyway, what you're looking for here is before_filter.

http://api.rubyonrails.com/classes/ActionController/Filters/ClassMethods.html

In Rails tradition the docs are lovely, but essentially you can do:

code:
before_filter :prepare_data
And prepare_data will get called before every action in that controller. You can also do:

code:
before_filter :authenticate, :except=>['login','register']
And it will get called for all actions except login and register. You can use :only to do the opposite. Pretty sweet! I believe the params hash is available here too.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
code:
sql = "SELECT p.* FROM payment AS p \
	LEFT JOIN school AS s ON p.schoolID = s.schoolID \
	LEFT JOIN cost AS c ON p.costID = c.costID \
	LEFT JOIN databaseInformation AS d on c.databaseID = d.databaseID
	WHERE s.schoolName LIKE '%school redacted%' && library NOT LIKE '%library also redacted%' \
	&& c.subscriptionStart >= '" + @dateStart.to_formatted_s(:db) + "' \
	&& c.subscriptionEnd <= '" + @dateEnd.to_formatted_s(:db) + "' \
	ORDER BY s.schoolName, s.library, d.databaseName"
					
@payments = Payment.find_by_sql(sql)
I don't know what hashappened, don't use camelCase, make sure you use properly named foreign keys, primary keys and this will work.

This won't work properly otherwise without a little bit of extra declarations in your model and such specifying the ruby-way ness. You may have to fix the pluralization, to make tables the ruby way have them all named in the pluralized sense.

Then to get information from it, pluralization starts to depends on what kind of relationship the tables have with one another. This should approximately begin to start to get at what you are going for. I think it might be a needlessly complex task, I don't know what the function of your application is so I can't tell.
code:
@payments = Payment.find(:all,
    :include => ["school", {"cost" => "database_information"}],
    :conditions => ["schools.name LIKE '%?%'
        AND schools.library NOT LIKE '%?%'
        AND costs.subscription_start >= ?
        AND costs.subscription_end <= ?",
      "school redacted", "library also redacted",
      @date_start.to_formatted_s(:db), @date_end.to_formatted_s(:db)],
    :order => "schools.name, schools.library, database_information.name")
A find method this large you are going to want to move it into your Payment model... as a start.

Good luck!

skidooer
Aug 6, 2001

zigb posted:

Rails 1.2.3 on Ruby 1.8.5. We're currently supporting another RoR app written by a different dev on this same box, so neither of those are subject to change. Also, I'm running in development mode.
It should load them then. Let the app automatically include the files if you aren't already. Manually loading them may cause problems.

zigb posted:

If there's some way AR would make this statement go away, I want to know about it!
Without knowing more about the problem at hand, I'd probably do something along these lines:
code:
class Payment < ActiveRecord::Base
  def self.find_subscriptions(start_date, end_date, options = {})
    options.reverse_merge!(
      :select     => 'payments.*',
      :joins      => construct_subscription_joins
      :conditions => construct_subscription_conditions(start_date, end_date)
    )
    
    find(:all, options)
  end
  
  def self.contruct_subscription_joins
    %(
      LEFT JOIN schools ON payments.school_id = schools.id
      LEFT JOIN costs ON payments.cost_id = costs.id
      LEFT JOIN database_informations ON costs.database_information_id 
         = database_informations.id
    )
  end
  
  def self.construct_subscription_conditions(start_date, end_date)
    statement = %(
      schools.school_name LIKE '% school redacted' AND
      library NOT LIKE '%library also redacted%' AND
      costs.subscription_start >= ? AND costs.subscription_end <= ?
    )
                  
    [ statement, range.first, range.last ]
  end
end

@payments = Payment.find_subscriptions(@start_date, @end_date,
      :order => 'school_name, library, database_name')
Not exactly beautiful yet, but it's a start. You can easily get rid of the SQL in construct_subscription_joins method, but I'll leave that as an exercise for the reader.

At very least take the SQL out of your controllers. The only place that belongs is in the model.

zigb posted:

Taking your second statement first, is a controller's initialize method not the best place to put code that I want executed for each action?
You want to use a before_filter for that.
code:
class MyController < ApplicationController
  before_filter :require_admin
  before_filter :initialize_some_object, :only => [ :index, :show ]

  private
    def require_admin
      redirect_to login_url unless current_user.admin?
    end

    def initialize_some_object
      @some_object = SomeObject.find(params[:some_object_id]
    end
end
And there are similar filters in ActiveRecord.

zigb posted:

You're saying that params is unavailable/nil in a controller's initialize method? Any specific reason why?
Yes. I'm guessing that it initializes the controller object before it sets the params, but I haven't read the code (or read the documentation :cool: ) to verify that suspicion.

skidooer fucked around with this message at 23:35 on Nov 20, 2007

Hop Pocket
Sep 23, 2003

I have a question about using forms. For this project I am doing, I have Events and Categories. An Event belongs_to a Category, so I have the event.category relationship.

In my Event form, I want to represent this as a select list. However, I am not really sure of the best way to go about it.

I'm currently trying:

code:
<%= f.select(:category, @categories.map {|c| [c.name,c.id]}) %>
And this renders the select list correctly when the form loads. However, upon submitting I get the error:

code:
Category expected, got String
Which is understandable, as it's trying to assign a String ID to the Category property of the Event model.

In Spring WebMVC, we used PropertyEditors to handle the conversion to and from ids and model objects. Is there anything like that in Rails? What's the 'normal' way to go about linking up a separate model object in a form?

Argue
Sep 29, 2005

I represent the Philippines
Shouldn't you just assign the id to the category_id property of Event? Or, you could do my_event.category = Category.find_by_id(the_id); I don't know which is the recommended way.

skidooer
Aug 6, 2001
You can assign the category_id field instead:
code:
<%= f.collection_select [b]:category_id[/b], @categories, :id, :name %>
Or if you're feeling real adventurous, you could change the model to do what you want.
code:
class Event < ActiveRecord::Base
  belongs_to :category
  
  def category_with_id_assignment=(category_id)
    category = case category_id
    when String, Fixnum
      Category.find(category_id)
    else
      category_id
    end
    
    self.category_without_id_assignment = category
  end
  alias_method :category_without_id_assignment=, :category=
  alias_method :category=, :category_with_id_assignment=
end
Remember that the user can enter any value they want for the category ID. It doesn't have to be a valid ID. So if you do directly assign the category_id into the database you run the risk of not having a valid association. By the same token, if the users are only allowed to select from a subset of categories, they can still pick from all of the categories without other checks and balances. So these are things that you must take into consideration when deciding how you're going to implement it.

skidooer fucked around with this message at 19:20 on Nov 21, 2007

Hop Pocket
Sep 23, 2003

Thanks guys. Assigning it to the category_id seems to work well.

Hop Pocket
Sep 23, 2003

You've all been really helpful. I have one more question. I'm writing my own form builder, and I want all of my form fields to go inside of a <table>. What I'd like to do is to:

code:
<% form_for :event, :builder=>EventFormBuilder, ..... do |f|  %>

  <% f.inside_table do %>
       
       <%= f.text_field... %>

  <% end>

<% end %>
I'm having trouble getting the inside_table method to do what I want. I essentially want it to be something like this:

code:

def inside_table
  puts "<table ...>"
  yield
  puts "</table>"
end

But of course puts outputs to the console. I can't figure out how to get inside_table to insert markup into the page. It's easy when you use <%= %> because you can just return the string, but helper methods using <% %> don't seem to work the same way.

vvvv thanks, that worked perfectly :cool:

Hop Pocket fucked around with this message at 16:10 on Nov 22, 2007

skidooer
Aug 6, 2001

Hop Pocket posted:

I have one more question. I'm writing my own form builder, and I want all of my form fields to go inside of a <table>.
code:
class EventFormBuilder < ActionView::Helpers::FormBuilder
  def inside_table(&block)
    @template.concat('<table>', block.binding)
    block.call
    @template.concat('</table>', block.binding)
  end
end

Evil Trout
Nov 16, 2004

The evilest trout of them all
One thing to consider is if you use Haml for markup (which I do and love), they have their own puts methods you can use in helpers, so your above code would work!

Hop Pocket
Sep 23, 2003

Grob posted:

One thing to consider is if you use Haml for markup (which I do and love), they have their own puts methods you can use in helpers, so your above code would work!

I'm looking at the Haml documentation right now.. Looks awesome. Though, my production host (DreamHost) does not have the Haml gem installed. I Haml'd my rails app and it looks like it installs a plugin that simply requires the gem.

Is there a way that I could install Haml on my project in a way that didn't require the gem to be installed on the production host?

Also, thanks!

edit: I think I figured it out:

guiness:events$ ruby script/plugin install http://svn.hamptoncatlin.com/haml/tags/stable --force

Hop Pocket fucked around with this message at 17:53 on Nov 22, 2007

ReelBigLizard
Feb 27, 2003

Fallen Rib
So I was pleasantly surprised to find rails 1.2.3 and sqlite3 installed as default when I upgraded to Leopard yesterday. Thanks, Apple (Thapple).

Hop Pocket
Sep 23, 2003

A question on rollbacks using capistrano. I have about 15 migrations in my source code, and I decided to change migration #7 to change the column names of a model object. On my development machine, I simply rake'd it back and then forward again:

$ rake db:migration VERSION=6
$ rake db:migrate

I then committed my code. How then to do the same through capistrano for the production host?

$ cap deploy:migrations VERSION=6

Did not work. It simply ran the migrations as if I had run

$ cap deploy:migrations

Ideas?

Sharrow
Aug 20, 2007

So... mediocre.
I'm not really surprised since it came from _why, but Hpricot is simply gorgeous. I refactored the parsing code of an old app using htmltokenizer and BeautifulSoup into about 10% of the size and run time. Being able to use CSS and XPath selectors for this sort of stuff is incredible.

ikari
May 17, 2003

Yeah, pretty much.

Hop Pocket posted:

A question on rollbacks using capistrano. I have about 15 migrations in my source code, and I decided to change migration #7 to change the column names of a model object. On my development machine, I simply rake'd it back and then forward again:

$ rake db:migration VERSION=6
$ rake db:migrate

I then committed my code. How then to do the same through capistrano for the production host?

$ cap deploy:migrations VERSION=6

Did not work. It simply ran the migrations as if I had run

$ cap deploy:migrations

Ideas?

The rule we follow on my team is that once a migration has been committed to SVN you should rarely go back and modify it to do things like change the column names. Between the time you committed and the time you decide to modify it, it could have been rolled out to testing, staging, and then production, not to mention other developer's machines. Unless there's a real good reason for doing otherwise, just add a new migration that alters the column names.

Hop Pocket
Sep 23, 2003

ikari posted:

The rule we follow on my team is that once a migration has been committed to SVN you should rarely go back and modify it to do things like change the column names. Between the time you committed and the time you decide to modify it, it could have been rolled out to testing, staging, and then production, not to mention other developer's machines. Unless there's a real good reason for doing otherwise, just add a new migration that alters the column names.

Yeah, I can see where you're coming from. In my situation though the production server is really just the staging server -- i.e. that's where i show my work to my clients that are usually remote. So it would not have any far-reaching consequences for the most part. Does Capistrano not have this ability?

vanjalolz
Oct 31, 2006

Ha Ha Ha HaHa Ha
Are there any good resources for Ruby + OpenGL or some 2D graphics library?
I've got things worked out with glut but I don't fancy trying to load a texture...
i've got a .c file which exports ruby functions to load a png, but no idea how to use it!

SeventySeven
Jan 18, 2005
I AM A FAGGOT WHO BEGGED EXTREMITY TO CREATE AM ACCOUNT FOR ME. PLEASE PELT ME WITH ASSORTED GOODS.
I've got a controller set up like this:

code:
def method1
  # Does some processing then...
  redirect_to :action => "method2"
end

def method2
  if request.xhr?
  elsif request.post?
  else
  end
end
Basically, I'm trying to determine the entry point for method2 (which can also come from the browser). Obviously I know about the request object, but is there any way I can tell if method2 was entered from a redirect?

MrSaturn
Sep 8, 2004

Go ahead, laugh. They all laugh at first...

SeventySeven posted:

I've got a controller set up like this:

code:
def method1
  # Does some processing then...
  redirect_to :action => "method2"
end

def method2
  if request.xhr?
  elsif request.post?
  else
  end
end
Basically, I'm trying to determine the entry point for method2 (which can also come from the browser). Obviously I know about the request object, but is there any way I can tell if method2 was entered from a redirect?

could you set a boolean value in method1 to true, so you know that when that value's true, it came from method 1? (then just reset it to false at the end of method 2)

Hammertime
May 21, 2003
stop

SeventySeven posted:

I've got a controller set up like this:

Basically, I'm trying to determine the entry point for method2 (which can also come from the browser). Obviously I know about the request object, but is there any way I can tell if method2 was entered from a redirect?

I'm sure there are ways of doing exactly what you want, but if possible you're better off not relying on a referrer.

Some alternatives:
- If you're just doing processing in method1, why not just render method2's template afterwards. Alternatively, break up the processing into a private non-rendering method and call it from method2.
- Write to the user's session collection at the end of method1, check/erase it in method2. This method is still flawed though, as if the user doesn't reach method2 after the redirect they'll have a session token sitting around unused.
- Though probably not what you're after, flashes can persist after a redirect.

SeventySeven
Jan 18, 2005
I AM A FAGGOT WHO BEGGED EXTREMITY TO CREATE AM ACCOUNT FOR ME. PLEASE PELT ME WITH ASSORTED GOODS.
Thanks for the advice guys. Wouldn't you know it though, there was actually a really easy way of doing it. I was unaware you could just append arbitrary parameters to a redirect_to so all I did was made it redirect_to :action => "method2", :temp => true and checked params[:temp] in method2.

poemdexter
Feb 18, 2005

Hooray Indie Games!

College Slice
I'm trying to write a barebones blog engine but am having trouble creating an admin section.

I've googled quite a bit for the last few days and all I can find are plugins that do multiple user accounts/login/register crap. All I really want is a table with my username and password and an admin controller that requires me to login before I can access the forms to create and destroy entries and messages.

I think the biggest problem I have is wrapping my head around REST and routes and MVC at the same time. I understand them individually but when mashed together, it gets confusing.

I have a blog controller that is routed to '' so when i go to https://www.somesite.com I get the index.rhtml of the blog. I want to have https://www.somesite.com/admin require a login and then I want to be able to mess with entries and messages. Can I create an admin controller that can access the new/create/destroy REST modules of Entry and Message models?

MrSaturn
Sep 8, 2004

Go ahead, laugh. They all laugh at first...
I've got another question: I'm trying to add an rss feed to my blog, but I'm missing something. In my blogposts controller, I added the following code (from http://paulsturgess.co.uk/articles/show/13-creating-an-rss-feed-in-ruby-on-rails):

code:
  def rss
    @blogposts = Blogpost.find(:all, :order=> "id DESC")
    render_without_layout
    @headers["Content=Type"] = "application/xml; charset utf-8"
  end
However, when I go to http://puddl.es:3002/blogposts/rss, I get "Can't find Blogpost: rss"

What'm I doing wrong? I've restarted my servers, I've tried putting the def rss in the frontpage's controller and moving the accompanying rss.rxml file to that view folder, and nothing seems to fix this.

Hop Pocket
Sep 23, 2003

MrSaturn posted:

I've got another question: I'm trying to add an rss feed to my blog, but I'm missing something. In my blogposts controller, I added the following code (from http://paulsturgess.co.uk/articles/show/13-creating-an-rss-feed-in-ruby-on-rails):

code:
  def rss
    @blogposts = Blogpost.find(:all, :order=> "id DESC")
    render_without_layout
    @headers["Content=Type"] = "application/xml; charset utf-8"
  end
However, when I go to http://puddl.es:3002/blogposts/rss, I get "Can't find Blogpost: rss"

What'm I doing wrong? I've restarted my servers, I've tried putting the def rss in the frontpage's controller and moving the accompanying rss.rxml file to that view folder, and nothing seems to fix this.

I'm not sure what could cause that problem, but here's my RSS implementation:

rss_controller.rb
code:
class RssController < ApplicationController
  def news
    @newsitems = Newsitem.find(:all, :order=>'created desc')
    render :layout=>false
  end
end
views/rss/news.rxml:
code:
xml.instruct! :xml, :version=>"1.0" 
xml.rss(:version=>"2.0"){
  xml.channel{
    xml.title("PeeOutside.org News")
    xml.link("http://peeoutside.org/rss/news")
    xml.description("Recent news from PeeOutside.org")
    xml.language('en-us')
      for newsitem in @newsitems
        xml.item do
          xml.title(newsitem.title)
          xml.category('General News')           
          xml.description(newsitem.body)           
          xml.pubDate(newsitem.created.strftime("%a, %d %b %Y %H:%M:%S %z"))
          xml.link('http://peeoutside.org/pee/newsitem/'  + newsitem.id.to_s)
          xml.guid('http://peeoutside.org/pee/newsitem/' + newsitem.id.to_s)
        end
      end
  }
}

Lamont Cranston
Sep 1, 2006

how do i shot foam

MrSaturn posted:

I've got another question

What do your routes look like for the blogposts controller? It looks like you have it set up for /blogposts/:id, which would explain why /blogposts/rss would screw up (it's looking for a post with id of "rss").

MrSaturn
Sep 8, 2004

Go ahead, laugh. They all laugh at first...
ah I got it working now, I just set it up under a new controller. Is RSS a reserved controller name?

if you want to see it, it's at http://puddl.es:3002/rssfeed

This is pretty cool. I'm learning how to do about one new thing a week on rails, given the free time I have. I do rather enjoy all this. I think next I'm going to work on my display pages for each blogpost, then do some interesting ajax stuff. You guys are great help so far! Thanks! :h:

skidooer
Aug 6, 2001

MrSaturn posted:

ah I got it working now, I just set it up under a new controller
Any reason why you didn't just include it in your index method?

code:
class BlogpostsController < ActionController::Base
  def index
    @blogposts = Blogpost.find(:all, :order=> "id DESC")

    respond_to do |type|
      type.html
      type.rss do
        render_without_layout
        headers["Content=Type"] = "application/xml; charset utf-8"
      end
    end
  end
end
Which, assuming you're using RESTful routes on that resource, will give you the URL http://host/blogposts.rss

Adbot
ADBOT LOVES YOU

skidooer
Aug 6, 2001
The discussion in the PHP thread about not putting any logic in the templates got me thinking. Would the template be better off separated from the view in Rails? I can imagine a RJS-like DSL for implementing the views. Something like the following:

View:
code:
unless @results.empty?
  @results.each do |result|
    page.insert :bottom, :results, page['/results/result'].yield(result)
  end

  page.hide :no_results
else
  page.hide :results
end
Template:
code:
<div id="no_results">
  <p>You have no results</p>
</div>

<div id="results">
  <div class="result">
    <p><%= result.name %></p>
  </div>
</div>
I'm not convinced it's better, but I do like some of the aspects of it. Thoughts?

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