0

This is an excerpt from a view -

  <%= @user.id %> is the user id
  <%= @book.id %> is the book id

  <div class="field">
     <%= f.select :contribtype, options_for_select(Contribution::CONTRIB_TYPES) %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

I have passed the parameters for the user and the book from previous views, such that I have

http://localhost:3000/contributions/new?book_id=1&user_id=5

as the URL for the form. The correct user_id and book_id are showing up on the page.

I have the following in the controller -

  def new
    @user = User.find_by_id(params[:user_id])
    @book = Book.find_by_id(params[:book_id])
    @contribution = Contribution.new(params[book_id: @book.id, user_id: @user.id])
  end

  def create
    @contribution = Contribution.new(contribution_params)
....

... but the user_id and book_id are not being captured in the object when it is created. I don't get any error, the data is simply not being set in the new object. Should I by passing parameters in the create action differently?

1 Answer 1

1

I'd use hidden fields as a quick fix:

@contribution = Contribution.new

in html:

<%= f.hidden_field :user_id, value: @user.id %>
<%= f.hidden_field :book_id, value: @book.id %>

be sure to permit those fields in your contribution_params

Sign up to request clarification or add additional context in comments.

4 Comments

I can't accept the answer for another seven minutes, but this has solved it for me. Do I infer from this that even if you have defined variables in the controller, the create action will only use params captured in fields on the submitted forms?
yes because your instance variable doesnt persist between requests, http its stateless (unless you use cookies/session)
Gotcha. Thanks very much for clearing that up for me :)
my pleasure, great to help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.