0
votes

I'm building a music album review site. I have the following models (relevant to this post):

  • Album
  • Artist
  • Review
  • User

  • Artists have many albums

  • Albums have many reviews
  • Users have many reviews

I have my forms all setup correctly and have the Reviews fields pulling into the album form. Everything is writing to the database correctly, but I have one problem: how do I set the user_id field dynamically to the current_user.id if it's a new review (only users can create reviews and users will only be admins, so there'll be 2-3 of us), but leave the field be if it's an existing review that populates when going to album#edit?

Right now I have:

<div class="field">
  <%= f.number_field :user_id, value: current_user.id %>
</div>
<div class="field">
  <%= f.label :content %><br />
  <%= f.text_area :content %>
</div>

Along with the rest of the fields and this works fine for a new review as that user_id field populates with the current_user.id value. However, when I go to edit the album, if I manually change the user_id value to be something else, save, go back and edit again, it resets to my user.id value (1, in this case).

Now, on the Album form itself, I'd just use a

if @album.new_record? ... end

statement to either pre-populate a hidden field with the current_user.id or do nothing for an existing record as I wouldn't want that to change.

But I can't figure out how to do the same thing for the nested fields and haven't been able to find anything by Googling. I've tried using f, builder, review, @review, self aand all have resulted in nil:nilClass errors. So how could I accomplish the same sort of thing for the nested reviews fields?

if nested_review.new_record?
  user_id = current_user.id
else
  user_id
end

I really hope this is something simple to do in the view that I'm just overlooking. It seems like it should be.

1

1 Answers

1
votes

You can access the existing user_id through f.object.

The following should help you accomplish what you want:

<%= f.number_field :user_id, value: (f.object.user_id || current_user.id) %>

Not sure why you've made this an editable-field though. Surely, it should be a hidden one.