views:

113

answers:

2

Currently, I have a 6-model ruby on rails application, that I added authlogic to. The overall setup is

User :has_many categories, topics,messages
Categories has_many topics,
Topics has_many messages

(With and the corresponding opposite belongs_to links).

When I try to access current_user.categories.find(2), no results are returned in the controller.

Furthermore, when I try to run this

current_user.topics.find(params[:topic_id]).messages.build

Then,

@msg = current_user.messages.build(params[:message])
@msg.save

It doesn't save the user_id from the has_many.

All features of this program were working before the current_user directives were added in.

Am I making a mistake with the setup? Or with the execution?

Because the association isn't saving after the build, could I later add the user_id field in the model?

Sorry about all the questions, and thanks in advance.

+1  A: 

I think your best bet is to go step-by-step. What does current_user return? Does the id of that user match one in your db? Does that user have any categories? Do any of them have an id of 2?

If you can isolate your problem to a single layer in your chained calls, it will be much easier to debug.

Kyle
I agree, that's a whole lot of coupling. You have no idea which of the many layers is breaking.It may also help to turn on ActiveRecord logging to see which queries are being generated.
Thanatos
A: 

Thanks Kyle. I've solved the problem using a filter in the model instead of using the controller to assign it on creation through association. Current_user simply returns the record of the current user using authlogic. I'm liking where the project is bow, and might deploy it after some visual tweaking, security, and more css :). Callbacks and filters are amazing with whatever you are developing. Also, if you need to get an variable from the application_controller to the model use the dollar sign ruby variable, not a class instance variable (at-sign). Rails is so easy compared to a roll-your-own Php or sintra app. Also, How many models are used for rails apps?

CodeJoust
If you're using dollar signs, you're walking down a dark road. Dollar signs are used for globals, and globals generally mean you're tightly coupling your classes.Not sure what you mean about how many models are used for Rails apps -- some projects probably have a handful, we have dozens, others have hundreds. Just depends on the scope of your app and maturity of your code base. A blog or Twitter requires significantly fewer models than Mint.com or something.
Kyle
I don't want to debug big apps quite yet. 6 models is enough for me.If I don't use a global, how can I get the current user object from the controller to the model? It's the only global in my app... And actually the first time I've needed one with ruby.
CodeJoust