ruby on rails - How to find nested attribute ID? -
how can show :user_id
of dueler in edit page?
edit.html.erb
<%= simple_form_for(@duel) |f| %> <%= @dueler.user_id %> <% end %>
rails c
duel.last id: 11, consequence: "bad", reward: "good", dueler.find(15) id: 15, user_id: 78, # want id challenge_id: 179, duel_id: 11, dueler.last id: 16, user_id: 15, challenge_id: 190, duel_id: 11,
duels_controller
@dueler = dueler.find(params[:user_id]) # gives error: activerecord::recordnotfound in duelscontroller#edit couldn't find dueler 'id'=
by request
full duels_controller
class duelscontroller < applicationcontroller before_action :set_duel, only: [:show, :edit, :update, :destroy] respond_to :html def index @duels = duel.joins(:duelers).all respond_with(@duels) end def show respond_with(@duel) end def new @duel = duel.new respond_with(@duel) end def edit @dueler = dueler.find_by(user_id: params[:dueler][:user_id]) # sri vishnu totakura's suggested change end def create @duel = duel.new(duel_params) @duel.save respond_with(@duel) end def update @duel.update(duel_params) respond_with(@duel) end def destroy @duel.destroy respond_with(@duel) end private def set_duel @duel = duel.find(params[:id]) end def duel_params params.require(:duel).permit(:consequence, :reward, duelers_attributes: [:id, :user_id, :challenge_id, :accept]) end end
since updated question, answer invalid! should have added controller actions initially! suggestion not work problem.
i'm not deleting answer because there discussion in comments.
you need use find_by
instead of find
.
find
queries on id
. if need find based on other columns, use find_by
your code should be:
@dueler = dueler.find_by(user_id: params[:dueler][:user_id])
documentation:
Comments
Post a Comment