Reputation: 1614
i have problem when i have to declare value for one of parameters in my permit and out of post form values . look at my code :
class QuoteController < ApplicationController
autocomplete :author, :name, :full => true
autocomplete :Category, :title, :full => true
def new
@quotes = Quote.new
end
def create
@quotes = Quote.new(quotesParams)
if @quotes.save
redirect_to root_url
else
redirect_to root_url
end
end
private
def quotesParams
params.require(:quote).permit(:text,:author_id, :category_id,
{:send_type => ["web"]},
{:user_id => [current_user.id])
end
end
but when i try to save in database send_type
and user_id
is null
Upvotes: 0
Views: 62
Reputation: 8318
Try the following code for your controller:
class QuoteController < ApplicationController
autocomplete :author, :name, :full => true
autocomplete :Category, :title, :full => true
def new
@quotes = Quote.new
end
def create
@quotes = Quote.new(quotesParams)
@quotes.send_type = "web"
@quotes.user_id = current_user.id
if @quotes.save
redirect_to root_url
else
redirect_to root_url
end
end
private
def quotesParams
params.require(:quote).permit(:text, :author_id, :category_id)
end
end
Upvotes: 0
Reputation: 434955
Strong parameters is more about the structure of the parameters than the actual parameter values. So things like:
{ :send_type => ["web"] }
{ :user_id => [current_user.id] }
don't assign default values, they're specifying the structure of nested values in params
.
I think you should handle your defaults in two places:
send_type
should default to 'web'
inside the model.user_id
should be required by the model but the controller should set the default (because that's who knows about current_user
.Something like this in your controller:
def create
@quotes = Quote.new(quotesParams) { |q| q.user_id = current_user.id }
#...
end
def quotesParams
params.require(:quote).permit(:text, :author_id, :category_id, :send_type)
end
and your model can default send_type
to 'web'
if the controller doesn't supply a value.
Upvotes: 1