ruby on rails 5 - NoMethodError in Controller#show - Nested model -
it might newbie question can't head around it. rails telling me method not defined if can access in console. i'm missing obviously...
here routes.rb file:
rails.application.routes.draw root 'static_pages#home' resources :users resources :bodies end end
here user model
class user < applicationrecord has_many :bodies, dependent: :destroy end
here body model
class body < applicationrecord belongs_to :user end
here bodies controller
class bodiescontroller < applicationcontroller def new @user = user.find(params[:user_id]) @body = @user.bodies.new end def create @body = current_user.bodies.build(body_params) if @body.save redirect_to user_body_path(@body) else render 'new' end end def show @user = user.find(params[:user_id]) @body = @user.bodies(params[:id]) end def index @bodies = body.all end private def body_params params.require(:body).permit(:weight, :sex, :age, :fat) end end
the create action working fine. i'm struggling show action work although right parameters passed along :
showing /users/rodolphegeant/code/ffl/app/views/bodies/show.html.erb line #9 raised: undefined method `sex' #<body::activerecord_associations_collectionproxy:0x007f820f65da90> did mean? send extracted source (around line #9): 7 8 9 10 11 12 hello body <%= @body.sex %> | <%= @body.age %> | <%= @body.weight %> | <%= @body.fat %> rails.root: /users/rodolphegeant/code/ffl application trace | framework trace | full trace app/views/bodies/show.html.erb:9:in `_app_views_bodies_show_html_erb___2597620731841156962_70098290142700' request parameters: {"user_id"=>"1", "id"=>"3"}
when go console can run @body.sex or @body.age or other method corresponds attributes i'm looking for....
thanks lot in advance helping me resolve issue.
codingly yours,
rodolphe
you should run find query on records return association user model.
def show @user = user.find(params[:user_id]) @body = @user.bodies.find(params[:id]) end
Comments
Post a Comment