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 开发者_如何学JAVAthing 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?
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.
In your controller action, set @loan.book_id to params[:id], then, in your template:
<%= f.hidden_field :book_id %>
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论