tomtom
tomtom

Reputation: 1190

How to structure Rails link so that clicking it will update an ActiveRecord attribute

I have two models in question, a Property model and an Application model. The application has_many properties, and the properties belongs_to application. As such, the Property model has an "application_id" field, which indicates the Application that is associated with the property.

I'd like to show a list of all possible Applications on the Property show page, with a link on the Application that, if clicked, will simply update application_id in the Property model to the ID of that application.

Here's my relevant code:

views/properties/show.html.erb

Choose an application template:
<ol class="microposts">
<% @owner.application.each do |template| %>
    <li><%= link_to "Application #{template.id}", :controller => "properties", :action => "update", :method => :put, :application_id  => template.id %></li>
<% end %>
</ol>

Edit - adding relevant property controller code

def show    
    @property=Property.find(params[:id])
    @owner=User.find(Property.find(params[:id]).user_id)
end

def update
    @property=Property.find(params[:id])
    if @property.update_attributes(property_params)
        flash[:success] = "Application added"
        redirect_to @property #going to change these redirects; this is just to get it working for now
    else
        redirect_to @property
    end
end

private

def property_params
    params.require(:property).permit(:address, :zip_code, :application_template_id)
end

This isn't working, though. Can somebody assist me with how I might tweak the link_to code so that it will do what I'm trying to do?

Upvotes: 1

Views: 401

Answers (1)

Richard Peck
Richard Peck

Reputation: 76774

Interesting question!

You'll want to do something like this:

#config/routes.rb
resources :properties do
   patch ("update_app/:application_id") #-> domain.com/properties/2/update_app/4
end

This will allow you to call:

#app/views/properties/show.html.erb
<%= link_to "Update", property_update_app_path(application_id), method: :patch %>

--

If you use the above link, you'll be able to use a controller as follows:

#app/controllers/properties_controller.rb
Class PropertiesController < ApplicationController
   def update_app
      @property = Property.find params[:id]
      @property.update({application_id: params[:app_id]})
   end
end

Upvotes: 2

Related Questions