1

I am trying to make sense of a pre-built app in which:

class Friendship < ActiveRecord::Base attr_accessible :status,:user,:friend belongs_to :user belongs_to :friend, :class_name => "User",:foreign_key => "friend_id" end 

I am confused by the attr_accessible part where he has supplied :user and :friend because they are not attributes in the friendship model. Is that just a short way for writing :user_id or friend_id or is he actually supplying the :user object and the :friend object? if they are indeed objects, what does that mean?

2 Answers 2

1

Instead of assigning a user_id or friend_id, it allows you to assign an user or a friend:

Friendship.create!(:status=>"active", :user=>current_user, :friend=>@friend) 

with attr_accessible :user_id,:friend_id, you would do this:

Friendship.create!(:status=>"active", :user_id=>current_user.id, :friend_id=>@friend.id) 

In short, both ways effectively save user_id and friend_id. Just different ways to do it.

Note: You should only make accessible the attributes you want to assign, otherwise you're potentially creating mass assignment vulnerabilities.

Sign up to request clarification or add additional context in comments.

Comments

1

It's not a short way of writing user_id. attr_accessible means, that you can mass assign a while user when creating a friendship. This means that with attr_accessible :status,:user,:friend you can do

Friendship.create! user: user1, friend: friend1 

without that attr_accessible an error would be thrown, because the mass assignment of user and friend is disabled

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.