habtm with created_on attr not being set

Greetings Railers,

I have a many-many defined as habtm from both sides of the equation. I've also set the join table with appropriate belongs_to defines.

I followed this example to make it work,

jrhicks.net/Projects/rails/has_many_and_belongs_to_many.pdf

which does work, for maintaining the many-many relationship records.

the relevant line is

@A.Bs = B.find(@params[:A_ids]) if @params[:A_ids]

but the problem is that in my many-many table I have a "created_on" field, as I'd like to track when this relationship is created.

Unfortunately this field is not getting auto-magically filled.

So, I'm wondering if this is due to the many-many type relationship not allowing (or supporting) this type of thing. Or is it the technique I'm using to maintain the relationship?

Or perhaps there is something completely different I'm not aware of, entirely possible as I've been doing Rails work for all of 2 weeks now.

I know that doing something like this leaves you totally open to SQL injection attacks:

contacts = Contact.find(:all, :conditions => "name = #{params[:name]")

and should be written this way instead:

contacts = Contact.find(:all, :conditions => ["name = ?", params[:name]])

but is this safe?:

contact = Contact.find(params[:id])

or should that be written as?:

contact = Contact.find(:first, :conditions => ["id = ?", params[:id]])

Thanks.

Best Regards,

Tamim

That's an excellent idea as well! I guess I was just curious whether the find by id was safe to start with. I don't want to add extra code if not needed. Going for the minimalist approach :slight_smile:

Best Regards,

Tamim
ruby n00bie

Daniel Jilg wrote:

Contact.find(params[:id]) sanitizes its input as you expect.

jeremy

However, ‘abc’.to_i == 0.

jeremy

Thanks for the clarification. That makes life much easier.

Best Regards,

Tamim
ruby n00bie

Jeremy Kemper wrote:

Because a record with id 0 may exist, whereas a record with id ‘abc’ cannot.

jeremy