0

(rails 2.2.2)

I have 2 models, user and subscription. Each user can have one ore more subscriptions (= premium services). Below the attributes:

  • user: id, username, ...
  • subscription: id, user_id (FK), type, started_at, ended_at

The classes:

class User < ActiveRecord::Base
  ..
  has_many :subscriptions, :dependent => :destroy
  ..
end

class Subscription < ActiveRecord::Base
  belongs_to :user, :foreign_key => :user_id
end

Now I want to make the UI part where existing users can subscribe in their account for the premium services. Therefore I wanted to make a first simple version where the user can subscribe by clicking on a checkbox. This is what I get so far

<div class = 'wrapper'>
  <%= render :partial => "my_account_leftbar" %>

  <% form_for @subscription, :url => subscribe_user_path(current_user) do |f| %>
  <div class="field">
    <%= (f.check_box :type?) %>      <!-- add '?'after the symbol, source: https://github.com/justinfrench/formtastic/issues/269 -->
  </div>

  <div class="actions">
    <%= f.submit "Subscribe", :class => "button mr8" %>
  </div>
  <% end %>
</div>

Problems:

  1. the app inserts a record into the db, but the attribute I defined in the form (type) has not been set (it should set '1' which stands for 'standard subscription') . How to get the app set this attribute?
  2. how to set the FK? I assume that rails should set the FK automatically, is that assumption correct?
  3. how to set the other values 'started_at' and 'ended_at? Those are datetime(timestamp) values...

Just run out of my beginner rails knowledge, any help really appreciated...

2 Answers 2

4

'Type' is a ruby on rails reserved word which should only be used when you are using Single Table Inheritance. You should rename your column name to something else.

Sign up to request clarification or add additional context in comments.

1 Comment

That worked, thanks. I also managed to get the other attributes saved.
2

I could solve the other questions 2 and 3 as well, wrapping it up:

  1. insert the record: as stated in the answer from Wahaj, renaming the column 'type' into e.g. 'subscription_type' helped. I created a seperate migration as described here: How can I rename a database column in a Ruby on Rails migration?

  2. storing the FK: updated the action in the controller. Instead of just writing

    @subscription = Subscription.new(params[:subscription])

    I wrote the following method to create a 'user's subscription'

    @subscription = current_user.subscriptions.build(params[:subscription])

  3. storing the 'started_at': added a method to the controller:

    @subscription.update_attributes(:started_at => Time.zone.now)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.