Question

I have models like this:

User
Paper
Subscription

As you can see there is has_many :through relationship and the Subscription stores :user_id and :paper_id

Paper has its own controller and its PapersController#index action lists all the available papers.

Now the real question

I want to add a "Subscribe" link next to every paper, which means to invoke the

SubscriptionsController#create

method.

In my PapersController#index

<td><%= link_to "Subscribe", subscriptions_path(paper),:method => :post %></td>

In my SubscriptionsController#create I have

    def create
        @subscription = current_user.subscriptions.build(subscription_params)
        if @subscription.save
          flash[:success] = "Paper Added to Profile"
          redirect_to root_url
        else
          render 'static_pages/home'
        end  
   end

When I look into the subscriptions table the :paper_id is nil, how can I get the :paper_id I am doing anything wrong?

Was it helpful?

Solution

Equivalent routes for link_to "Subscribe", subscriptions_path,:method => :post is

POST   /subscriptions(.:format)                              subscriptions#create

So, you have to pass the paper_id explicitly. Have a look at link_to.

Update your link to <td><%= link_to "Subscribe", subscriptions_path(paper_id: paper.id),:method => :post %></td>

And Instead of

@subscription = current_user.subscriptions.build(subscription_params)

its should be (as paper_id is not under subscription namespace, you can access it directly)

@subscription = current_user.subscriptions.build({paper_id: params[:paper_id]})

OTHER TIPS

Please have a try with following.

def create
        paper = Paper.where(id: params[:id]).first
        @subscription = current_user.subscriptions.push(paper)
        flash[:success] = "Paper Added to Profile"
        redirect_to root_url
   end

Recheck your params value from server console or by debugging. I think you may be supply paper as separate parameter like params[:paper_id] but you build @subscription instance only by subscription_params that is not the value of paper_id. For this purpose modify your create action like this

@subscription = current_user.subscriptions.build(subscription_params.marge({:paper_id => params[:paper_id]})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top