Search code examples
ruby-on-railsruby-on-rails-3has-many

Rails 3, how to setup has_many form and Controller action


I have these Models

class User #( Devise)
  has_many :codes 
  has_many :redemptions
end

class Code
  belongs_to :band
  belongs_to :user
  has_many :redemptions
end

class Redemption
  has_one :code
  belongs_to :user
end

class Band
  has_many :codes
end

I am trying to do most of the work in the Band#show view. So I have a band_controller action redeem.

My goal is that the current_user (provided by devise) inputs a code into a form input (created by another user) and submits to the Band#redeem action and puts the user_id and code_id into a redeem object. This creates a redemption.

The crazy piece of this is that one user creates a code, another redeems it. I have the Redemption model built.

<%= form_for @band, :url => {:action => "redeem"}, do |f|  %>
  <%#= f.text_field  :code  %>
  <%= f.submit 'Submit' %>
<% end %> 

It's the current form I have setup. This obviously doesn't work but it's what I am trying to wire up.


Solution

  • Instead of having a redeem-action on BandsController, I suggest you simply use RedemptionsController#create. Something like the following:

    class BandsController < ApplicationController
      def show
        @band       = Band.find(params[:id])
        @redemption = Redemption.new(code: @band.codes.first)
      end
    end
    
    # in bands/show template
    <%= form_for @redemption do |f| %>
      <%= f.hidden_field :code_id %>
      <%= f.submit "Redeem now" %>
    <% end %>
    

    This form will POSTto RedemptionsController#create where you simply create the redemption.