Can I protect access to a relationship?


#1

Hi,

I have a class Match that looks like this (simplified)

class Match < ActiveRecord::Base

belongs_to :opp1, :class_name => “Player”, :foreign_key => “opp1_id”
belongs_to :opp2, :class_name => “Player”, :foreign_key => “opp2_id”
belongs_to :winner, :class_name => “Player”, :foreign_key => “winner_id”

end

Can I prevent code from doing this?

@match.winner = @some_player

You can protect attributes from mass assignment, but that’s not good
enough in this case…

Jeroen


#2

Hi,

On 09/02/06, Jeroen H. removed_email_address@domain.invalid wrote:

@match.winner = @some_player
You have several ways of preventing such behaviour:

class Match < ActiveRecord::Base
def winner
case self.who_won
when ‘home’ then self.opp1
when ‘guest’ then self.opp2
else nil
end
end
end


#3

I am trying to validate a record without saving it. How can that be
accomplished?

Thanks,

Willi


#4

Valid? Gives me true or false, but I need the errors associated to each
column.


#5

Once you’ve done object.valid? you can do object.errors to get the
validation errors, can’t you?


#6

use valid?

http://api.rubyonrails.com/classes/ActiveRecord/Validations.html


#7

Thanks,

That actually works, I somehow missed that.

Willi

Subject: Re: [Rails] How can I force the validation of a record
withoutsavingit?

Once you’ve done object.valid? you can do object.errors to get the
validation errors, can’t you?

On 2/9/06, Willi Weichselbaumer < removed_email_address@domain.invalid
mailto:removed_email_address@domain.invalid > wrote:

Valid? Gives me true or false, but I need the errors associated to each
column.