开发者

Where should I put the code?

开发者 https://www.devze.com 2023-04-09 15:39 出处:网络
I have the models User and StoredItem: class UserData < ActiveRecord::Base has_many :stored_items, :dependent => :destroy

I have the models User and StoredItem:

class UserData < ActiveRecord::Base
  has_many :stored_items, :dependent => :destroy
end

class StoredItem < ActiveRecord::Base
  belongs_to :user
  named_scope :lookup, lambda { |id| { :conditions => ['qid = ?', id]}}
end

I need to have two methods to add and remove the items to StoredItem for current user. I put this code to User model开发者_Python百科:

class UserData < ActiveRecord::Base
  has_many :stored_items, :dependent => :destroy

  def save_item(params)
    if(!self.stored_items.lookup(params[:qid]).exists?)
      item = self.stored_items.new(:sid => params[:qid],
                                   :name => params[:qti],
                                   :url => params[:qur],
                                   :group_id => params[:title],
                                   :rating => Integer(params[:rating]))
      item.save
    end
  end

  def remove_item(qid)
    item = self.stored_items.lookup(qid).first()
    item.destroy
  end
end

So here is the StoredItem controller:

def save_item
  @user = UserData.find_by_login(session[:cuser])
  @user.save_item(params)
  # ...
end

Is it good architectural decision or it will be better to put this code to StoredItem model and pass the current user into it?


This is a good architectural decision. You need to keep it in the user since the User is the owner of the StoredItem. The user is responsible for its stored items, not the other way around.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号