kwh941
kwh941

Reputation: 235

Update attribute on a has_many relationship

I am printing a list of user's contacts and want to give the user the ability to mark each contact as "done". (Essentially marking them off their to do list).

How do I update the :done attribute for the specific contact?

This is form with a hidden field is not working:

<% if current_user.contacts.any? %>
<% current_user.contacts.each do |c| %> 
    <li id="<%= c.id %>">
        <%= c.name %><br/>

        <%= form_for(@contact) do |f| %>
            <%= f.hidden_field :done, :value=>true %>
            <%= f.submit "Mark as done", class: "btn btn-small btn-link"%>
        <% end %>

    </li>
<% end %>

I get this error:

Template is missing Missing template contacts/create, application/create with {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :coffee]}. Searched in: * "C:/Sites/rails_projects/sample_app/app/views"

This is my contacts controller:

def create
  @contact = current_user.contacts.build(params[:contact])
  if @contact.save
    flash[:success] = "Contact saved!"
    redirect_to root_url
  else
    flash[:error] = "Something is wrong"
  end
end

Upvotes: 1

Views: 580

Answers (1)

PinnyM
PinnyM

Reputation: 35533

For some reason, perhaps due to validation rules, the @contact object can't be saved. In this case, the else branch in your create action doesn't specify what to render, so it's looking for a create template. You may be able to simply add a line to render :action => :new or redirect_to :action => :new, assuming your new action doesn't require preloading additional data.

else
  flash[:error] = "Something is wrong"
  redirect_to :action => :new
end

You can also use respond_with instead of explicitly redirecting, which will render the new action if errors were found:

def create
  @contact = current_user.contacts.build(params[:contact])
  if @contact.save
    flash[:success] = "Contact saved!"
  else
    flash[:error] = "Something is wrong"
  end
  respond_with @contact, :location => root_url
end

Upvotes: 1

Related Questions