views:

29

answers:

0

Hi,

I have a (rails 3) application that allows users to query for books. I have three models: query, result, book with a has_many :through relation both ways:
query has many books through result and book has many queries through results

When I enter a query and click OK, I get a form to create a book using the query phrase. I want the books_controller#create to use the query id to create a result with book_id = the book's id and query_id = the passed in query's id. The form looks as follows:

<%= form_for(@book) do |f| %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class='field'>
 <%= f.hidden_field :query_id, :value => @query_id%>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

And in the books controller, I have:

def create
    @book = Book.new(params[:book])
    query = Query.find(params[:query_id])
    if(@book && query)
      result = Result.new
      result.book = @book
      result.query = query
      result.save!
      ...
    end
end

On submitting this form, I get the error:

ActiveRecord::UnknownAttributeError in BooksController#create

unknown attribute: query_id

(on line @book = Book.new(params[:book])

My question is: how do I pass through the query id to the book creation action so I can construct the result record there?

Update: Found a solution: I used the form_for with url to pass in the param instead of form field as follows:

<%= form_for(@book,:url => {:action => 'create',:query_id => @query.id}) do |f| %>

Is there a better way to do this?

Thanks Anand