Monday, 15 February 2010

ruby on rails - Associating new model with user id -



ruby on rails - Associating new model with user id -

i'm (very) new ror , have read many tutorials issue none seem work. i'm trying allow 1 user create 1 booth sell things.

this db migration:

class createbooths < activerecord::migration def alter create_table :booths |t| t.string :name t.references :user, index: true t.timestamps null: false end add_index :booths, [:user_id] end end

here booth controller:

class boothscontroller < applicationcontroller before_action :logged_in_user def new @booth = booth.new end def create @booth = current_user.booths.build(booth_params) if @booth.save flash[:success] = "congrats on opening booth!" redirect_to root_url else render 'new' end end private def booth_params params.require(:booth).permit(:name) end end

and booth model:

class booth < activerecord::base belongs_to :user validates :user_id, presence: true end

i added user model:

has_one :booth, dependent: :destroy

when include validates :user_id, presence: true won't save db. when exclude it, saves not include user id in database. if still reading give thanks , hope can help!

you need alter create method of boothscontroller this:

def create @booth = current_user.build_booth(booth_params) if @booth.save flash[:success] = "congrats on opening booth!" redirect_to root_url else render 'new' end end

here, have one-to-one association between user , booth, , that's why have instantiate booth current_user using build_<singular_association_name>, build_booth , pass params it: build_booth(booth_params).

booths.build(booth_params) works one-to-many association, example: user has many booths, not vice versa.

ruby-on-rails

No comments:

Post a Comment