Note that there are some explanatory texts on larger screens.

plurals
  1. PORuby on Rails: many-to-many relationship
    primarykey
    data
    text
    <p>I have a database with 3 tables: User, Card, Cardset:</p> <pre><code>User has_many Cards User has_many Cardsets Card belongs_to User Cardset belongs_to User Card has_and_belongs_to_many Cardsets Cardset has_and_belongs_to_many Cards </code></pre> <p>A card is basically a "flashcard", it has card.term and card.definition columns.</p> <p>In the view card/new.html, in which the logged in user can create new cards, I created the following form:</p> <pre><code>&lt;%= form_for(@card) do |f| %&gt; &lt;%= f.label :term, "Termin" %&gt; &lt;%= f.text_field :term %&gt; &lt;%= f.label :definition, "Definicja" %&gt; &lt;%= f.text_area :definition %&gt; &lt;%= f.label :cardset, "Dodaj automatycznie do setu:" %&gt; &lt;%= select("cardset", :id, current_user.cardsets.all.collect {|p| [ p.name, p.id ] }, {:include_blank =&gt; true}) %&gt; &lt;br&gt; &lt;%= f.submit "Dodaj kartę!", class: "btn btn-large btn-primary" %&gt; &lt;% end %&gt; </code></pre> <p>The problematic line is this:</p> <pre><code>&lt;%= select("cardset", :id, current_user.cardsets.all.collect {|p| [ p.name, p.id ] }, {:include_blank =&gt; true}) %&gt; </code></pre> <p>I want this to be a drop down menu containing all the sets that belong to the user who is creating the new card. When users chooses a set from this list and clicks submit, the relation (a many-to-many relation, in table: Cards_Cardsets) between the new card and the chosen cardset is automatically created.</p> <p>In my card_controller I have:</p> <pre><code>def create @card = current_user.cards.build(params[:card]) @cardset = Cardset.find_by_id(params[:cardset]) @card.cardsets&lt;&lt;@cardset if @card.save flash[:success] = "Utworzono karte!" render 'show' else flash.now[:error] = 'Uzupelnij pola.' render 'new' end end </code></pre> <p>The line:</p> <pre><code>@cardset = Cardset.find_by_id(params[:cardset]) </code></pre> <p>is suposed to return the chosen cardset. But instead, it returns this error:</p> <pre><code>Unknown key: id app/controllers/cards_controller.rb:8:in 'create' </code></pre> <p>if I hardcode the id into this line like this:</p> <pre><code>@cardset = Cardset.find_by_id(3) </code></pre> <p>it then works. So i guess the problem is caused by this expression:</p> <pre><code>params[:cardset] </code></pre> <p>How can I get it to work?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload