我正在尝试生成一个创建新对象的链接。它创建了对象,但没有设置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
答案 0 :(得分:1)
我猜你的错误就在这里:
# in create
@subscription = Subscription.new(params[:subscription])
您没有为subscription
参数设置值。您设置了params[:user_id]
和params[:subreddit_id]
。在创建订阅时使用它们,例如:
@subscription = Subscription.new(
user_id: params[:user_id],
subreddit_id: params[:subreddit_id]
)