开发者

Using the save method together with update_attributes. Is this common?

开发者 https://www.devze.com 2023-03-07 14:15 出处:网络
A user can sign up as an artist. All the user needs to do now, is provide his email. In Artist controller, def create. Is it normal to have something like:

A user can sign up as an artist. All the user needs to do now, is provide his email.

In Artist controller, def create. Is it normal to have something like:

  def create
    @artist = current_user

    respond_to do |format|
      if @artist.update_attributes(params[:user]) # params[:user] contains email
        @artist.is_artist = true
        @artist.save
....

In my User model, I have:

attr_accessible :email

Which means, I can't simply do @art开发者_运维问答ist.update_attributes(:is_artist => true). I would have to use the save method instead. Is this type of approach common? Or is there a better way?


You can define before_create method in your model:

class User < ActiveRecord::Base
  ...
  before_create :fill_fields
  def fill_fields
    is_artist = true
  end
end


I would do the following:

1st: I wound not set up an ArtistController if you do not have an Artist Model. rather I would add a non-restful method in your UserController, and push the implemention logic into the model ...

   # config/routes.rb
   resources :users do
     member {post 'signup_as_artist'}
   end

   # UserController

   def signup_as_artist
     @user = User.find(params[:id])
     @user.signup_as_artist
   end

  # User

  def signup_as_artist
    self.update_attribute :is_artist, true
  end

Good luck

0

精彩评论

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