0

i have this form:

<%= form_for(@candy) do |f| %>
  <div class="">
    <%= current_user.totalcandy %>
  </div>
  <div class="">
    <%= f.label :candy, 'add a candy' %><br />
    <%= f.number_field :candy%>
  </div>
  <div class="">
    <%= f.submit('ADD') %>
  </div>
<% end %>

how do i add that input value into totalcandy and save it? Thanks

2
  • 1
    Why are you using class=""? You can just omit the class attribute if you don't have a value for it. Commented Jan 13, 2014 at 5:18
  • create a virtual attribute to the model and add an input field. Commented Jan 13, 2014 at 10:28

1 Answer 1

1

You're getting confused with how Rails works

  1. Rails is server-side
  2. You're trying to calculate client-side
  3. You have to process them separately

Modularity

You'll have to calculate this on the back-end (once you've submitted the form)

Rails views are there to show an HTML page, and won't change unless a request is performed to the server

In keeping with Rail's modular structure, you need to keep your logic in your controller, your inputs in your views, and your data manipulation in your models. Therefore, you only need to pass the different Candy's to your controller, allowing it to sum the total:

#app/views/candys/new.html.erb
<%= form_for(@candy) do |f| %>
    <%= f.label :candy, 'Add a candy' %>
    <%= f.number_field :candy%>
    <%= f.submit %>
<% end %>

#app/controllers/candys_controller.rb
def new 
    @candy = Candy.new
end 

def create
    @candy = Candy.new(candy_params)
    @candy.save

    @total_candy = #your logic here
end

private

def candy_params
    params.require(:candy).permit(:candy)
end
Sign up to request clarification or add additional context in comments.

Comments

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.