Reputation: 777
Is there any way on manually doing the "create" function? I have an scaffold, (model/controller/view), so what I want to do is to change a little bit the parameters that the user gave me.
def create
@meme = Meme.new(params[:meme])
respond_to do |format|
if @meme.save
format.html { redirect_to @meme, notice: 'Meme was successfully created.' }
format.json { render json: @meme, status: :created, location: @meme }
else
format.html { render action: "new" }
format.json { render json: @meme.errors, status: :unprocessable_entity }
end
end
end
Is there any way of doing something like:
def create
@meme = Meme.new
@meme.name = params([:name])
@meme.id = params([:id])
@meme.url = @[email protected]
respond_to do |format|
if @meme.save
format.html { redirect_to @meme, notice: 'Meme was successfully created.' }
format.json { render json: @meme, status: :created, location: @meme }
else
format.html { render action: "new" }
format.json { render json: @meme.errors, status: :unprocessable_entity }
end
end
end
So as you can see in the last example I want to save a URL concatenating the name and the id, is there any way of achieving this from the controller.
Thanks in advance.
Upvotes: 0
Views: 4778
Reputation: 28574
The code you are looking for is kind of a combination of both of your samples:
def create
@meme = Meme.new(params[:meme])
@meme.url = "#{@meme.name}-#{@meme.id}"
respond_to do |format|
if @meme.save
format.html { redirect_to @meme, notice: 'Meme was successfully created.' }
format.json { render json: @meme, status: :created, location: @meme }
else
format.html { render action: "new" }
format.json { render json: @meme.errors, status: :unprocessable_entity }
end
end
end
I threw in a dash between the name and the id just for kicks.
You might also want to think about doing this in a before_save
hook inside the Meme model, that would be a cleaner solution than having it in the controller. Good luck!
Upvotes: 3