views:

52

answers:

2

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?

+2  A: 

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

<%= f.hidden_field :book_id %>

John Douthat
User should be using restful routing for this. A hidden field is a hack.
Ryan Bigg
+2  A: 

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.

John Topley
And then you'd need to do something similar in the create action too.
Ryan Bigg
Ryan is correct. I've updated my answer accordingly.
John Topley