0

I'm trying to implement a quote saving feature in a Rails app. I have a User Model that has_many :quotes and a Quote Model that belongs_to :user. Now I have a separate Book Model that would be the source of these quotes.

Within the Book's show.html.erb file, I have a form to save quotes for the current user

<%= form_for (@new_quote) do |f| %>
<div class="field">
    <%= f.hidden_field :book_id, :value => @new_comment.book_id %>
    <%= f.text_field :body %>
</div>
<div class="actions">
    <%= f.submit %>
</div>
<% end %>

And in the Book controller, I have

def show
    @new_quote = current_user.quotes.create(book_id: params[:id])
end

The quote saves fine but the problem is, since I have this Quote creation statement in the show method, everytime I go to the show.html.erb page of my Book model, it creates a Quote with an empty body.

What can I do to solve this? I was thinking it probably would involve moving this Quote creation to the actual create method of the Quote controller but I don't know how to exactly pass the parameters through.

1 Answer 1

1

You could just build that quote, but not save it to the database. Then the user need to send the form to save that record. Just change your show method to:

def show
  @new_quote = current_user.quotes.build(book_id: params[:id])
end
Sign up to request clarification or add additional context in comments.

2 Comments

Hm I tried that and it seems to save everything but the id of the current_user. So when I look at current_user.quotes, the new quote doesn't show up.
Nevermind, I found out I just had to add another hidden field to the form which passed in the current_user id. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.