Possible to add a form into another models view in rails

不打扰是莪最后的温柔 提交于 2019-12-11 15:01:43

问题


I have a very small application I ma building in rails. It is a simple weight tracker app. I have created a User model which has a sign up page. Once the user logs in they are redirected to the user#show view. Here is the user controller so far:

class UsersController < ApplicationController
before_filter :authenticate_user!

def show
  @user = current_user
end

end

I have 2 other models one is a Weight model and the other a Goal model, I would like it so what when a user signs up they are presented with a screen asking them to type in the current weight and goal weight this information will then be store in the Weight and Goal models respectively along with the logged in users ID.

So far I have been able to add a form to the user show.html.erb template :

<%= form_for @user do |f| %>

  <%= f.fields_for :weight do |builder| %>
    <fieldset>
      <%= f.label :value, "Current weight" %><br />
      <%= f.text_field :value %><br />
    </fieldset>
  <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Which renders the form correctly but when I then click on the submit button it simply goes to an error page saying Unknown action- The action 'update' could not be found for UsersController. Im assuming iM doing something wrong as it should try and send to the create action.

Is there anyone out there who could help me back on the right path, Im very much a noob at rails.


回答1:


You are using the form_for Rails helper and passing @user to it, because @user is a persistent model (saved in the db) then the generated form will have the action to /users/:id with PUT method so the request will be sent to an action named update in your UsersController, it seems that you don't have that action defined in your UsersController

it should be somthing like the following:

def update
  @user = Users.find(params[:id])
  if @user.update_attributes(params[:user])
  # do something if saving succeeds
  else
  # do something if saving fails
  end
end



回答2:


Well this has nothing to do with all your models. This pertains to the fact you have not defined an update method in your controller.

When you have done that look into accepts_nested_attributes_for if you want to nest models.

Besides all that, a show page usually shows a read only for of the object. An edit page has the editable form of the object.




回答3:


I believe, after searching for this question having similar issues, that it is not update that is missing but edit.

I know this is an old thread, and you have probably solved the issue, but if not try adding this:

def edit

    @user = User.find(params[:id])

end


来源:https://stackoverflow.com/questions/15098036/possible-to-add-a-form-into-another-models-view-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!