从链接创建对象不实现参数

时间:2012-06-16 21:14:28

标签: ruby-on-rails ruby-on-rails-3

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

1 个答案:

答案 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]
)