简体   繁体   中英

Is there a more elegant way to do this in Rails (has_one association)

Hey, I'm very new to Ruby and Rails. I was wondering if I was doing this the right way.

@user = User.new(params[:user])
@student.user = @user
@student.save
if @user.save
  ...rest of the code

In my app, a Student has one User, and each User belongs to a Student (think of a User as an Account). The association itself isn't my question though; is the block of code above the best way to save a new User that's associated to a Student?

I'm surprised nobody mentioned the right way.

@user = @student.build_user(params[:user])

if @user.save
   # ... rest of the code ...
end

This way @user will be built already associated with @student.

If the correspondence between user and student is 1:1 may be this relationship is redundant. (maybe I'm missing something).

A cooler approach would be perform all the operations you need to the user object and then the last one would be:

@student.user = @user
@student.save

I think you have @ -overload here. Only use @ if you want to make the variable an instance variable of the class, rather than a local variable that only exists inside your function. Anyway, here's one possible way to do it:

@student.user = User.create(params[:user])
@student.save

if @student.user.new_record?
  # didn't get saved...
end

ActiveRecord::Base#create creates a new object, tries to save it to the database, and then returns the object, and is a useful shortcut for the new-save pattern. It always returns the object, though, so you need to ask whether or not it was successfully saved, hence new_record? .

If the Student has_one User, then you should put the foreign key on the User. As in, the User will have the student_id column in the database. A user_id column on the Student isn't necessary.

In which case you can just do this:

@user = User.new(params[:user])
@user.student = @student
if @user.save
  ...rest of the code

And you won't even need to modify @student .

The question that comes up for me is whether the relationship between Student and User is a has-a or an is-a relationship. It has to do with object modeling of the domain problem.

I suspect it may be is-a, in which case you don't want has_one and belongs_to--known as "composition"--but instead Single-Table Inheritance (STI)--known as "inheritance".

The questions to ask are: 1. Is a Student also a User, ie does a Student have the same attributes and methods as a User, plus more methods or restrictions? Since in this case the Student IS also a user, the question of whether a Student can have 0, 1 or more Users does not apply. 2. Does the Student "have" a User in the sense that it could also have 0 Users, or perhaps more than 1?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM