Ok so I have a few models that need to interact with each other -
Blog, Post, and User.  I'll get their relationships out of the way:

Blog
  has_many :posts
  has_and_belongs_to_many :users (by way of a join table, a blog can
have many contributing users)

Post
  belongs_to :blog
  belongs_to :user (the author of the post)

User
  has_and_belongs_to_many :blogs (a user can contribute to many blogs)
  has_many :posts


I'm running into a problem when validating posts; I want to ensure
that the logged in user we find in the session is listed as a
contributor to the blog they are trying to post to.  I added some
validation to my Post model, that appears to be failing when editing
an existing post.  Post creation, curiously, seems to pass the
validation test.

I should note that @user is a variable set by my ApplicationController
using a before_filter.  really sure what's going on here, so any help
is appreciated.  I'm guessing the @user set by my app controller
probably isn't accessible by the Post class.

Anyhow, here's my Post model:

class Post < ActiveRecord::Base
  belongs_to :blog
  belongs_to :user
  has_many :comments

  validate :user_can_contribute

private
  def user_can_contribute
    if @user.nil?
      logger.info("@user hasn't been set yet!")
    end

    if !blog.users.include?(@user)
      errors.add(:user, "You cannot contribute to this blog.")
    end
  end
end

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to rubyonrails-t...@googlegroups.com.
To unsubscribe from this group, send email to 
rubyonrails-talk+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to