Matthew Berman
Matthew Berman

Reputation: 8631

Getting no method error when trying to read attribute from join model

I have projects and users joined via has_many :through join model called ownerships. Each ownership has an owner_type attribute that I want to access.

I want to have a way to pass a user_id to a project model and get the owner_type via the ownership join model. And visa versa I want to pass a project_id to a user model and get the owner_type via the ownership join model. Here is what I have:

class Project < ActiveRecord::Base
  attr_accessible :name, :description

  has_many :ownerships
  has_many :users, :through => :ownerships

  validates :name, :presence => true,
                   :length => { :maximum => 50 }

  def owner_type?(user_id)
    @user_id = user_id
    @ownership = self.ownerships.where(:user_id => @user_id)
    @ownership.owner_type
  end

end

class User < ActiveRecord::Base
  attr_accessible :name, :email, :admin

  has_many :ownerships
  has_many :projects, :through => :ownerships

  accepts_nested_attributes_for :projects

  email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i

  validates :name, :presence => true,
                   :length => { :maximum => 50 }

  #validates :email, :presence => true,
  #                  :format => { :with => email_regex },
  #                  :uniqueness => { :case_sensitive => false }

  validates_inclusion_of :admin, :in => [true, false]

  def self.create_with_omniauth(auth)
    create! do |user|
      user.provider = auth["provider"]
      user.uid = auth["uid"]
      user.name = auth["user_info"]["name"]
      user.admin = false
    end
  end
end

class Ownership < ActiveRecord::Base
  attr_accessible :owner_type

  belongs_to :project
  belongs_to :user

  validates :user_id, :presence => true

  validates :project_id, :presence => true

  validates :owner_type, :presence => true

end

and then in my project#show page:

<%= @project.owner_type?(current_user.id) %>

what am I doing wrong? How do I access the owner_type attribute from the ownership model from anywhere? It never works.

Upvotes: 0

Views: 914

Answers (1)

Chirantan
Chirantan

Reputation: 15634

You haven't pasted the actual error you are getting. But here is what I think is going wrong.

ownerships is a has_many relationship. It will return you a collection of results, always. Thus, @ownership = self.ownerships.where(:user_id => @user_id) will return you an array. So you should probably be doing if you expect only 1 result.

@ownership = ownerships.where(:user_id => @user_id).first
@ownership.owner_type

This should work.

Upvotes: 1

Related Questions