开发者

Rails help create has many and belongs to assoction

开发者 https://www.devze.com 2023-03-06 05:32 出处:网络
Here is m开发者_C百科y user model: class User < ActiveRecord::Base has_many :posts end Here is my post model:

Here is m开发者_C百科y user model:

class User < ActiveRecord::Base
has_many :posts
end

Here is my post model:

class Post < ActiveRecord::Base
before_create :ejer
belongs_to :user
def ejer
    self.user.build
end
end

I am using devise and when I have signed in and trying to create a post i gets this error:

NoMethodError in PostsController#create

undefined method `build' for nil:NilClass

I have created a column user_id in posts table.

Why do I get the error and how do I assoctie current user that is signed in with the post?


self.user will be nil so you're trying to run the method build on nil which will raise an exception like you're getting.

To add a user to the post you can just assign it by setting the attribute:

def ejer
  self.user = User.new
end

You could also use the build_user method

def ejer
  build_user
end

Or set the user to an existing user:

def ejer
  self.user = User.first
end


Judging by your comments in response to Mario you don't actually want to build a new user - that would create a new record.

I recommend taking a look at the sentient_user gem. Once you've hooked it up correctly in the models and controllers your posts model can become:

class Post < ActiveRecord::Base

  belongs_to :user
  validates :user, :presence => true

  before_validate do
    self.user ||= User.current_user
  end
end

I changed the hook to be before_validate and added a validation to ensure that there is a user associated since in most cases it doesn't make sense to allow a post to be created without a user id.

(oh and I'm sure there are other solutions to getting a User.current_user or equivalent, sentient_user is just the one I personally use.)

0

精彩评论

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