user6945851 user6945851 - 1 month ago 7
Ruby Question

stuck in an edit method with rails

I'm stuck in an easy edit method and can't go on until I solve it.

I have a list of items in the index view, each item has a view item button, a delete button, and an edit button.

I have no problem with create, show and delete, but I'm stuck with te edit method.

this is my activities_controller.rb

def edit
@activity = Activity.find(params[:id])
if @activity.update(activity_params)
redirect_to @activity
else
redirect_to :edit
end
end

private

def activity_params
params.require(:activity).permit(:name, :description)
end


and this is the edit view:

<%= form_for(@activity) do |f| %>
<p>
<%= f.text_field :name %>
<%= f.label :name, "Name" %>
</p>
<p>
<%= f.text_area :description" %>
<%= f.label :description, "Descripction" %>
</p>
<p>
<%= f.submit "save", class: "btn" %>
</p>




In the list of items view:

<% @activities.each do |activity| %>
<%= activity.name %>
<%= link_to "edit", edit_activity_path(activity), class: "btn"%>
<% end %>


In all the examples I followed they do the edit button in the show item view, so they use @activity as a path param, but in my loop I can't use @activity and I use
activity
. I think here is my noob fail but I can't figure how to fix it.

So when I enter to for example localhost:3000/activities/11/edit it shows me the message "param is missing or the value is empty: activity".

As I said before I think it is because I am passing as a path param activity instead of @activity and then it has not the structure I did for the strong param "activity_params". But at this moment I don't see the solution.

Answer

The problem isn't the instance variable, using activity as opposed to @activity is fine. The problem is that the edit action is used to show the form, you have it confused with the update action, which would be used to actually update the model.

def edit
    @activity = Activity.find(params[:id])
end

def update
    @activity = Activity.find(params[:id])
    if @activity.update(activity_params)
        redirect_to @activity
    else
        render :edit
    end
end

is closer to what you are probably intending/trying to do.