开发者

has_many association rails

I have a User model and a Job_Category model, the Job_C开发者_开发知识库ategory model

belongs_to :user

The User model

has_many :job_categories, :dependent => :destroy   

I have a Dashboard Controller and am trying to display all the Job_Categories for a specific logged in User.

class DashboardController < ApplicationController
before_filter :authenticate_user!


def index
 @user = User.find(params[:id])
 @job_categories = @user.job_categories


 #@job_categories = JobCategory.all

 #respond_to do |format|
#   format.html # index.html.erb
#   format.xml  { render :xml => @job_categories }
# end

end

However, when I am trying to display this I get the error 'Couldn't find User without an ID' . I see this in the log:

Processing by DashboardController#index as HTML User Load (0.3ms) SELECT "users".* FROM "users" WHERE ("users"."id" = 2) LIMIT 1 Completed in 22ms

ActiveRecord::RecordNotFound (Couldn't find User without an ID): app/controllers/dashboard_controller.rb:9:in `index'


First of all, you cannot try to find by params in console, because there ain't such thing.

Try this in console:

User.find(2)

(..default column where find method looks the value is primary key which I assume is id as usual)

Then another thing, if you're already authenticating user in before_filter, you might already have @current_user or something set, are you using some authentication plugin like devise or something? So there's no need to pass current users id to dashboard controller. Application controller already knows who this user is and your dashboard controller is a subclass of it.

And ensure your job_category table has user_id column too.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜