views:

18

answers:

2

I did a bunch of gutting to my default controllers and now I can't get my user_id to populate on create.

I was curious how that gets populated. If you're interested, take a look at my routes, and model assocations, and then at then end I'll show you the resulting params..The end result is no user_id being added.

routes

resources :users do
  resources :posts do
    collection do
      get :view
    end
  end
end

models

#Post.rb
belongs_to                    :user, :touch => true                    
#User.rb
has_many :posts

I navigate to this url..

http://localhost:3001/users/1/posts/new

and place my post, and the params return this :

{"commit"=>"save", "post"=>{"name"=>"hell hath no furry", "category"=>"vegan", "url"=>"www.reddit.com", "text"=>"", "is_link"=>"1"}, "authenticity_token"=>"aYnSLgJ9E6MaM6iSkRrCyyiMZj06oLdybTMkNqss8FA=", "utf8"=>"✓", "action"=>"create", "controller"=>"posts"}

This was working before, not sure why its not associating them anymore.

Any ideas?

+1  A: 

In your form_for, are you passing in the @user?

form_for([@user, @post]) do

Maybe this will help:

http://www.gatezero.org/blog/2008/4/30/rails-nested-resources-and-form_for.html

njorden
Hmm.. I wasn't previously, and it still worked..
Trip
Also, you can take a look at the last example under "Resource-oriented style" on http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for
njorden
Ah yes, just did actually and found something that works and looks good. I'll post the answer here, but i'm curious still if there's something better.
Trip
A: 

Hmm I don't like answering my own questions, but I found this solution, and was wondering if this is an acceptable way of accomplishing this.

In my controller for def create , I do this :

@post = current_user.posts.create(params[:post])

instead of this :

@post = Post.new(params[:post])
Trip
Yep, that looks like a great way to do it. If you're doing it based on the current_user (I wasn't sure), you may want to make the resource mapping singular, because you're not using the user_id in the route at all. http://guides.rubyonrails.org/routing.html#singular-resources
njorden