woolagaroo
woolagaroo

Reputation: 1522

How to set a predefined value in a form in Rails

So I just got started in Rails, and I'm trying to create an Object (a book_loan in my case) with a Form. The thing is that I get to this form by clicking on a book, so I pass the book_id as a parameter, like localhost:3000/loans/new?id=1.

Now I don't want the user to be able to set the book id field in the form, since I already know the id. So my question is how to set the value in the form. I have been trying things like:

<% form_for(@loan) do |f| %>
  <%= f.error_messages %>
  ...
  <%= @loan.book_id = params[:id] %>
  <%= f.submit 'Create' %>
<% end %>

without any success. Does anybody have a hint for me?

Upvotes: 2

Views: 1575

Answers (2)

John Topley
John Topley

Reputation: 115292

In your controller's create action, you can get hold of the book instance and then build a new loan through the association, passing in the values submitted from the form. Something like this:

def new
  @loan = Loan.new
end

def create
  book = Book.find(params[:id])
  @loan = book.loans.build(params[:loan])
  @loan.save # etc...
end

Because you're building the new loan through the association, it will have the correct book_id set on it.

Upvotes: 5

John Douthat
John Douthat

Reputation: 41179

In your controller action, set @loan.book_id to params[:id], then, in your template:

<%= f.hidden_field :book_id %>

Upvotes: 2

Related Questions