Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Ruby
can this be more succinct?
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Florian Aßmann, post: 4573143"] Hi eggie5, Just a minor thingy, rename timestamp_start column to created_at and Rails does its magic. So you can write (categories replaced with category_ids!): (params[:category_ids] || []).each do |category_id| @subscriber.subscriptions.create(:category_id => category_id, :is_subscribed => true) end You can also put a verify in the class definition of your controller: class SubscriptionsController < ApplicationController verify :params => :category_ids, :method => :post, :only => :subscribe, :redirect_to => :back def subscribe # ... # both String and Array do have the each method... params[:category_ids].each do |category_id| @subscriber.subscriptions.create(:category_id => category_id, :is_subscribed => true) end # ... end # ... end You can even move this whole bunch of code to the subscribers model itself: class Subscriber < ActiveRecord::Base # This methods accepts multiple category ids in form of: # instance.subscribe 1, 2, 4, ... def subscribe(*category_ids) # wrap insertion of multiple records in a transactions is generally # a good idea... ActiveRecord::Base.transaction do category_ids.each do |category_id| subscriptions.create(:category_id => category_id, :is_subscribed => true) end end end end class SubscriptionsController < ApplicationController verify :params => :category_ids, :method => :post, :only => :subscribe, :redirect_to => :back def subscribe # ... @subscriber.subscribe(*params[:category_ids]) # ... end # ... end Or extend the association with a module, see AssociationExtensions in ActiveRecord::Associations::ClassMethods. in this case you could write something like: instance.subscriptions.category_ids = category_ids This encapsulate all methods in a module that are only important for the association itself - it's clean! If you don't use ActionPack and ActiveRecord at all don't mind this post... Regards Florian P.S. Beware, this code was not run through any functional or unit tests... [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Ruby
can this be more succinct?
Top