cheng
cheng

Reputation: 1324

Creating a Model in Rails within the controller of a different Model

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.

Upvotes: 0

Views: 47

Answers (1)

spickermann
spickermann

Reputation: 106882

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

Upvotes: 1

Related Questions