我正在尝试生成一个创建新对象的链接。它创建对象,但不设置 user_id 或 subreddit_id。
<%= link_to ' (add to my subreddits)',
{
controller: 'subscriptions',
action: 'create',
user_id: current_user.id,
subreddit_id: subreddit.id
},
method: :post %>
以下是相关的控制器:
def new
@subscription = Subscription.new
unless current_user.admin?
@subscription.user_id = current_user.id
end
respond_to do |format|
format.html # new.html.erb
format.json { render json: @subscription }
end
end
def create
@subscription = Subscription.new(params[:subscription])
unless current_user.admin?
@subscription.user_id = current_user.id
end
respond_to do |format|
if @subscription.save
format.html { redirect_to @subscription, notice: 'Subscription was successfully created.' }
format.json { render json: @subscription, status: :created, location: @subscription }
else
format.html { render action: "new" }
format.json { render json: @subscription.errors, status: :unprocessable_entity }
end
end
end