Reputation: 1022
I'm trying to refactor my code according Rails Best Practice. Now I'm face with a problem where I have two instance variable at controller and I can't move them to the model. Here we are:
feedbacks_controller.rb
def get_feedback
...
@employee = Employee.find_by(:name)
if @employee.blank?
...
else
@client_feedback = Feedback.new(:screen_name => @screen_name, :feedback => @feedback)
@client_feedback.employee_id = @employee.id
@client_feedback.client_id = @employee.client_id
@client_feedback.location_id = @employee.location_id
@client_feedback.save
According to Rails Best practice Move Model Logic into the Model all assignments inside the else need move to the model, my doubt is how I will start the @employee
instance variable inside of model?
Upvotes: 0
Views: 230
Reputation: 2965
If you have a relation between Employee and Feedback you can do something like this
if you have has_one relation
@client_feedback = @employee.feedbacks.new(screen_name: @screen_name, feedback: @feedback)
@client_feedkback.save
if you have has_many relation
@employee.feedbacks << Feedbacks.new(screen_name: @screen_name, feedback: @feedback)
@employee.save
About the others fields (client and location ids) seems that you have reduntant data. Try to keep that data in a single place.
ADDED
In your model you have client_id and location_id, if you really need them on Feedback model you can do something like
@employee.feedback = Feedback.new(screen_name: @screen_name, feedback: @feedback, client_id : @employee.client_id, location_id:@employee.location_id )
@employee.save
Upvotes: 1