0

我正在尝试生成一个创建新对象的链接。它创建对象,但不设置 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
4

1 回答 1

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]
)
于 2012-06-16T21:43:23.383 回答