Rails - How to create multiple “matches” in one action between a user and opportunities? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experience Should we burninate the [wrap] tag?How can I rename a database column in a Ruby on Rails migration?How do I get the current absolute URL in Ruby on Rails?declerative_authorization on User problemlink_to :action => 'create' going to index rather than 'create'multiple joins in railsNo route matches “/users/sign_out” devise rails 3set current user when creating a comment with inherited_resource railsrails how to show catery name if user select sub_category?rails 4. how to create actions using relationships between three models?Rails cannot Create Record with Active Record Associations

Models of set theory where not every set can be linearly ordered

How to draw this diagram using TikZ package?

Why is black pepper both grey and black?

Gastric acid as a weapon

Is there a service that would inform me whenever a new direct route is scheduled from a given airport?

What would be the ideal power source for a cybernetic eye?

When to stop saving and start investing?

Did Kevin spill real chili?

WAN encapsulation

Do I really need recursive chmod to restrict access to a folder?

Does surprise arrest existing movement?

Are my PIs rude or am I just being too sensitive?

What's the purpose of writing one's academic bio in 3rd person?

When is phishing education going too far?

What are the pros and cons of Aerospike nosecones?

How to bypass password on Windows XP account?

How much radiation do nuclear physics experiments expose researchers to nowadays?

Can inflation occur in a positive-sum game currency system such as the Stack Exchange reputation system?

How to find all the available tools in macOS terminal?

Why is "Consequences inflicted." not a sentence?

How can whole tone melodies sound more interesting?

Is there a way in Ruby to make just any one out of many keyword arguments required?

What does the "x" in "x86" represent?

What are the motives behind Cersei's orders given to Bronn?



Rails - How to create multiple “matches” in one action between a user and opportunities?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experience
Should we burninate the [wrap] tag?How can I rename a database column in a Ruby on Rails migration?How do I get the current absolute URL in Ruby on Rails?declerative_authorization on User problemlink_to :action => 'create' going to index rather than 'create'multiple joins in railsNo route matches “/users/sign_out” devise rails 3set current user when creating a comment with inherited_resource railsrails how to show catery name if user select sub_category?rails 4. how to create actions using relationships between three models?Rails cannot Create Record with Active Record Associations



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'm looking for the easiest and the most clever way to create interest_id(match) in one-click.



Here is my MVC :



user.rb



class User < ApplicationRecord
has_many :interests, through: :opportunities
end


interest.rb



class Interest < ApplicationRecord
belongs_to :opportunity
belongs_to :user
end


opportunity.rb



class Opportunity < ApplicationRecord
has_many :interests
end


InterestsController.rb



def create
@user = current_user
@opportunities = Opportunity.all
@interest = Interest.new(interest_params)
if @interest.save!
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice:"it doesn't work"
end
end

def interest_params
params.permit(
:user_id,
:opportunity_id)
end


user/show



<%= link_to "Match", user_interests_path(@user), class:"btn btn-primary", :method => :post %>


For now, I can't pass opportunities (nil). Could you please advise me about the easiest way to create interests? (New on RoR for 6 months).
Many thanks for your help.










share|improve this question
























  • Why do you want to use a link instead of a form with checkboxes?

    – MrShemek
    Mar 8 at 16:17







  • 1





    How Interest can have opportunity_ids if it belongs to (one) Opportunity ?

    – Sovalina
    Mar 8 at 16:19











  • At term, I would like to generate Interest automatically, on callbacks. Exact for opportunity_ids, I'm editing.

    – Maceoz
    Mar 8 at 16:30

















1















I'm looking for the easiest and the most clever way to create interest_id(match) in one-click.



Here is my MVC :



user.rb



class User < ApplicationRecord
has_many :interests, through: :opportunities
end


interest.rb



class Interest < ApplicationRecord
belongs_to :opportunity
belongs_to :user
end


opportunity.rb



class Opportunity < ApplicationRecord
has_many :interests
end


InterestsController.rb



def create
@user = current_user
@opportunities = Opportunity.all
@interest = Interest.new(interest_params)
if @interest.save!
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice:"it doesn't work"
end
end

def interest_params
params.permit(
:user_id,
:opportunity_id)
end


user/show



<%= link_to "Match", user_interests_path(@user), class:"btn btn-primary", :method => :post %>


For now, I can't pass opportunities (nil). Could you please advise me about the easiest way to create interests? (New on RoR for 6 months).
Many thanks for your help.










share|improve this question
























  • Why do you want to use a link instead of a form with checkboxes?

    – MrShemek
    Mar 8 at 16:17







  • 1





    How Interest can have opportunity_ids if it belongs to (one) Opportunity ?

    – Sovalina
    Mar 8 at 16:19











  • At term, I would like to generate Interest automatically, on callbacks. Exact for opportunity_ids, I'm editing.

    – Maceoz
    Mar 8 at 16:30













1












1








1








I'm looking for the easiest and the most clever way to create interest_id(match) in one-click.



Here is my MVC :



user.rb



class User < ApplicationRecord
has_many :interests, through: :opportunities
end


interest.rb



class Interest < ApplicationRecord
belongs_to :opportunity
belongs_to :user
end


opportunity.rb



class Opportunity < ApplicationRecord
has_many :interests
end


InterestsController.rb



def create
@user = current_user
@opportunities = Opportunity.all
@interest = Interest.new(interest_params)
if @interest.save!
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice:"it doesn't work"
end
end

def interest_params
params.permit(
:user_id,
:opportunity_id)
end


user/show



<%= link_to "Match", user_interests_path(@user), class:"btn btn-primary", :method => :post %>


For now, I can't pass opportunities (nil). Could you please advise me about the easiest way to create interests? (New on RoR for 6 months).
Many thanks for your help.










share|improve this question
















I'm looking for the easiest and the most clever way to create interest_id(match) in one-click.



Here is my MVC :



user.rb



class User < ApplicationRecord
has_many :interests, through: :opportunities
end


interest.rb



class Interest < ApplicationRecord
belongs_to :opportunity
belongs_to :user
end


opportunity.rb



class Opportunity < ApplicationRecord
has_many :interests
end


InterestsController.rb



def create
@user = current_user
@opportunities = Opportunity.all
@interest = Interest.new(interest_params)
if @interest.save!
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice:"it doesn't work"
end
end

def interest_params
params.permit(
:user_id,
:opportunity_id)
end


user/show



<%= link_to "Match", user_interests_path(@user), class:"btn btn-primary", :method => :post %>


For now, I can't pass opportunities (nil). Could you please advise me about the easiest way to create interests? (New on RoR for 6 months).
Many thanks for your help.







ruby-on-rails crud






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 8:20









Magnus Melwin

79011122




79011122










asked Mar 8 at 16:14









MaceozMaceoz

63




63












  • Why do you want to use a link instead of a form with checkboxes?

    – MrShemek
    Mar 8 at 16:17







  • 1





    How Interest can have opportunity_ids if it belongs to (one) Opportunity ?

    – Sovalina
    Mar 8 at 16:19











  • At term, I would like to generate Interest automatically, on callbacks. Exact for opportunity_ids, I'm editing.

    – Maceoz
    Mar 8 at 16:30

















  • Why do you want to use a link instead of a form with checkboxes?

    – MrShemek
    Mar 8 at 16:17







  • 1





    How Interest can have opportunity_ids if it belongs to (one) Opportunity ?

    – Sovalina
    Mar 8 at 16:19











  • At term, I would like to generate Interest automatically, on callbacks. Exact for opportunity_ids, I'm editing.

    – Maceoz
    Mar 8 at 16:30
















Why do you want to use a link instead of a form with checkboxes?

– MrShemek
Mar 8 at 16:17






Why do you want to use a link instead of a form with checkboxes?

– MrShemek
Mar 8 at 16:17





1




1





How Interest can have opportunity_ids if it belongs to (one) Opportunity ?

– Sovalina
Mar 8 at 16:19





How Interest can have opportunity_ids if it belongs to (one) Opportunity ?

– Sovalina
Mar 8 at 16:19













At term, I would like to generate Interest automatically, on callbacks. Exact for opportunity_ids, I'm editing.

– Maceoz
Mar 8 at 16:30





At term, I would like to generate Interest automatically, on callbacks. Exact for opportunity_ids, I'm editing.

– Maceoz
Mar 8 at 16:30












2 Answers
2






active

oldest

votes


















0














If I understand correctly your relation schema, the Interest is the join record associating a User to (eventually) many Opportunity, and vice-versa (many-to-many relationship).



With that being said (and please correct me if I am wrong), you can do the following to achieve what you want:



# in user/show
<% @opportunities.each do |opportunity| %>
<%=
link_to "Match opportunity #opportunity.id",
user_interests_path(@user, opportunity_id: opportunity.id),
class: "btn btn-primary",
method: :post
%>
<% end %>

# in interests_controller
def create
if current_user.interests.create(opportunity_id: opportunity_id_param)
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice: "it doesn't work"
end
end

private

def opportunity_id_param
params.require(:opportunity_id)
end


This suggested code:



  • requires the opportunity_id param for the interests#create action

  • use current_user to automatically set the user_id on the Interest model, so the end-users can't send a user_id that are not theirs (if they could, then each user could create interest for other users without their agreement... security flaw)


On a side note, I strongly advise you to not select all existing Opportunity record and display it on your page: it does not scale. Someday, you will end up with hundreds of Opportunity records, making this list too big from a User Experience perspective.



I suggest a smarter approach, for example some kind of ordering + limit: max of 10 records ordered by "most interest", which can be accomplished by the following:



# in controller
@popular_opportunities = Opportunity
.joins('LEFT JOINS interests ON interests.opportunity_id = opportunities.id')
.order('count(interests.*) DESC, opportunities.id')
.limit(10)


And then in the view, simply use @populator_opportunities instead of @opportunities.



Other options, like pagination, are also efficient in this case but IMO relevant ordering is the minimum.






share|improve this answer

























  • Exact. It seems to work. I have just an undefined method 'fetch' for string which just appeared when clicked but it generated the good numbers of buttons.

    – Maceoz
    Mar 8 at 16:47











  • @Maceoz I updated my answer with the fixed code. I was not expecting that ActionController::Parameters.new(a: 1).require(:a) would return the value, but a copy of the hash with only allowed/required key/value pairs

    – MrYoshiji
    Mar 8 at 17:02












  • Thank you ! I'm on the way, I can now see the opportunity_id in the parameters. An other error appeared but due to my nested associations (HasManyThroughNestedAssociations). Probably a problem on my models (has_many like suggested by Alan).

    – Maceoz
    Mar 8 at 17:22











  • @Maceoz yes, a User has_many :interests and therefore it also has_many :opportunities, through: :interests

    – MrYoshiji
    Mar 8 at 17:47



















-1














First, you need to pass the ids of the opportunities you want to create interest some way, the best is a form, with checkboxes like MrShemek said, or a multi select dropdown.



I think you probably made some mistakes in User and Opportunity with the has_many and belong_to part:



class User < ApplicationRecord
has_many :interests
has_many :opportunities, through: :interests
# interest is the one that links user and opportunity, it has the references for both user and opportunities
end
class Opportunity < ApplicationRecord
has_many :interests
has_many :users, through: :interests
end


then in controller you could do



def create
@user = current_user
@opportunities = Opportunity.all
@user.opportunity_ids = interest_params[:opportunity_ids] # it will create the interrests automatically for the given ids (because the relations of has_many through)
if @user.save!
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice:"it doesn't work"
end
end





share|improve this answer























  • the ids writers are dangerous. they have persistence effect: User.first.opportunity_ids = [] will actually trigger DELETE statements without even running validations or callbacks, and still do it even though you did not save the user object. Yep, that's crazy, I know... Don't use _ids generated methods on update (because it works properly on create)

    – MrYoshiji
    Mar 8 at 16:55












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55066998%2frails-how-to-create-multiple-matches-in-one-action-between-a-user-and-opport%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














If I understand correctly your relation schema, the Interest is the join record associating a User to (eventually) many Opportunity, and vice-versa (many-to-many relationship).



With that being said (and please correct me if I am wrong), you can do the following to achieve what you want:



# in user/show
<% @opportunities.each do |opportunity| %>
<%=
link_to "Match opportunity #opportunity.id",
user_interests_path(@user, opportunity_id: opportunity.id),
class: "btn btn-primary",
method: :post
%>
<% end %>

# in interests_controller
def create
if current_user.interests.create(opportunity_id: opportunity_id_param)
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice: "it doesn't work"
end
end

private

def opportunity_id_param
params.require(:opportunity_id)
end


This suggested code:



  • requires the opportunity_id param for the interests#create action

  • use current_user to automatically set the user_id on the Interest model, so the end-users can't send a user_id that are not theirs (if they could, then each user could create interest for other users without their agreement... security flaw)


On a side note, I strongly advise you to not select all existing Opportunity record and display it on your page: it does not scale. Someday, you will end up with hundreds of Opportunity records, making this list too big from a User Experience perspective.



I suggest a smarter approach, for example some kind of ordering + limit: max of 10 records ordered by "most interest", which can be accomplished by the following:



# in controller
@popular_opportunities = Opportunity
.joins('LEFT JOINS interests ON interests.opportunity_id = opportunities.id')
.order('count(interests.*) DESC, opportunities.id')
.limit(10)


And then in the view, simply use @populator_opportunities instead of @opportunities.



Other options, like pagination, are also efficient in this case but IMO relevant ordering is the minimum.






share|improve this answer

























  • Exact. It seems to work. I have just an undefined method 'fetch' for string which just appeared when clicked but it generated the good numbers of buttons.

    – Maceoz
    Mar 8 at 16:47











  • @Maceoz I updated my answer with the fixed code. I was not expecting that ActionController::Parameters.new(a: 1).require(:a) would return the value, but a copy of the hash with only allowed/required key/value pairs

    – MrYoshiji
    Mar 8 at 17:02












  • Thank you ! I'm on the way, I can now see the opportunity_id in the parameters. An other error appeared but due to my nested associations (HasManyThroughNestedAssociations). Probably a problem on my models (has_many like suggested by Alan).

    – Maceoz
    Mar 8 at 17:22











  • @Maceoz yes, a User has_many :interests and therefore it also has_many :opportunities, through: :interests

    – MrYoshiji
    Mar 8 at 17:47
















0














If I understand correctly your relation schema, the Interest is the join record associating a User to (eventually) many Opportunity, and vice-versa (many-to-many relationship).



With that being said (and please correct me if I am wrong), you can do the following to achieve what you want:



# in user/show
<% @opportunities.each do |opportunity| %>
<%=
link_to "Match opportunity #opportunity.id",
user_interests_path(@user, opportunity_id: opportunity.id),
class: "btn btn-primary",
method: :post
%>
<% end %>

# in interests_controller
def create
if current_user.interests.create(opportunity_id: opportunity_id_param)
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice: "it doesn't work"
end
end

private

def opportunity_id_param
params.require(:opportunity_id)
end


This suggested code:



  • requires the opportunity_id param for the interests#create action

  • use current_user to automatically set the user_id on the Interest model, so the end-users can't send a user_id that are not theirs (if they could, then each user could create interest for other users without their agreement... security flaw)


On a side note, I strongly advise you to not select all existing Opportunity record and display it on your page: it does not scale. Someday, you will end up with hundreds of Opportunity records, making this list too big from a User Experience perspective.



I suggest a smarter approach, for example some kind of ordering + limit: max of 10 records ordered by "most interest", which can be accomplished by the following:



# in controller
@popular_opportunities = Opportunity
.joins('LEFT JOINS interests ON interests.opportunity_id = opportunities.id')
.order('count(interests.*) DESC, opportunities.id')
.limit(10)


And then in the view, simply use @populator_opportunities instead of @opportunities.



Other options, like pagination, are also efficient in this case but IMO relevant ordering is the minimum.






share|improve this answer

























  • Exact. It seems to work. I have just an undefined method 'fetch' for string which just appeared when clicked but it generated the good numbers of buttons.

    – Maceoz
    Mar 8 at 16:47











  • @Maceoz I updated my answer with the fixed code. I was not expecting that ActionController::Parameters.new(a: 1).require(:a) would return the value, but a copy of the hash with only allowed/required key/value pairs

    – MrYoshiji
    Mar 8 at 17:02












  • Thank you ! I'm on the way, I can now see the opportunity_id in the parameters. An other error appeared but due to my nested associations (HasManyThroughNestedAssociations). Probably a problem on my models (has_many like suggested by Alan).

    – Maceoz
    Mar 8 at 17:22











  • @Maceoz yes, a User has_many :interests and therefore it also has_many :opportunities, through: :interests

    – MrYoshiji
    Mar 8 at 17:47














0












0








0







If I understand correctly your relation schema, the Interest is the join record associating a User to (eventually) many Opportunity, and vice-versa (many-to-many relationship).



With that being said (and please correct me if I am wrong), you can do the following to achieve what you want:



# in user/show
<% @opportunities.each do |opportunity| %>
<%=
link_to "Match opportunity #opportunity.id",
user_interests_path(@user, opportunity_id: opportunity.id),
class: "btn btn-primary",
method: :post
%>
<% end %>

# in interests_controller
def create
if current_user.interests.create(opportunity_id: opportunity_id_param)
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice: "it doesn't work"
end
end

private

def opportunity_id_param
params.require(:opportunity_id)
end


This suggested code:



  • requires the opportunity_id param for the interests#create action

  • use current_user to automatically set the user_id on the Interest model, so the end-users can't send a user_id that are not theirs (if they could, then each user could create interest for other users without their agreement... security flaw)


On a side note, I strongly advise you to not select all existing Opportunity record and display it on your page: it does not scale. Someday, you will end up with hundreds of Opportunity records, making this list too big from a User Experience perspective.



I suggest a smarter approach, for example some kind of ordering + limit: max of 10 records ordered by "most interest", which can be accomplished by the following:



# in controller
@popular_opportunities = Opportunity
.joins('LEFT JOINS interests ON interests.opportunity_id = opportunities.id')
.order('count(interests.*) DESC, opportunities.id')
.limit(10)


And then in the view, simply use @populator_opportunities instead of @opportunities.



Other options, like pagination, are also efficient in this case but IMO relevant ordering is the minimum.






share|improve this answer















If I understand correctly your relation schema, the Interest is the join record associating a User to (eventually) many Opportunity, and vice-versa (many-to-many relationship).



With that being said (and please correct me if I am wrong), you can do the following to achieve what you want:



# in user/show
<% @opportunities.each do |opportunity| %>
<%=
link_to "Match opportunity #opportunity.id",
user_interests_path(@user, opportunity_id: opportunity.id),
class: "btn btn-primary",
method: :post
%>
<% end %>

# in interests_controller
def create
if current_user.interests.create(opportunity_id: opportunity_id_param)
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice: "it doesn't work"
end
end

private

def opportunity_id_param
params.require(:opportunity_id)
end


This suggested code:



  • requires the opportunity_id param for the interests#create action

  • use current_user to automatically set the user_id on the Interest model, so the end-users can't send a user_id that are not theirs (if they could, then each user could create interest for other users without their agreement... security flaw)


On a side note, I strongly advise you to not select all existing Opportunity record and display it on your page: it does not scale. Someday, you will end up with hundreds of Opportunity records, making this list too big from a User Experience perspective.



I suggest a smarter approach, for example some kind of ordering + limit: max of 10 records ordered by "most interest", which can be accomplished by the following:



# in controller
@popular_opportunities = Opportunity
.joins('LEFT JOINS interests ON interests.opportunity_id = opportunities.id')
.order('count(interests.*) DESC, opportunities.id')
.limit(10)


And then in the view, simply use @populator_opportunities instead of @opportunities.



Other options, like pagination, are also efficient in this case but IMO relevant ordering is the minimum.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 8 at 17:07

























answered Mar 8 at 16:28









MrYoshijiMrYoshiji

45.5k99594




45.5k99594












  • Exact. It seems to work. I have just an undefined method 'fetch' for string which just appeared when clicked but it generated the good numbers of buttons.

    – Maceoz
    Mar 8 at 16:47











  • @Maceoz I updated my answer with the fixed code. I was not expecting that ActionController::Parameters.new(a: 1).require(:a) would return the value, but a copy of the hash with only allowed/required key/value pairs

    – MrYoshiji
    Mar 8 at 17:02












  • Thank you ! I'm on the way, I can now see the opportunity_id in the parameters. An other error appeared but due to my nested associations (HasManyThroughNestedAssociations). Probably a problem on my models (has_many like suggested by Alan).

    – Maceoz
    Mar 8 at 17:22











  • @Maceoz yes, a User has_many :interests and therefore it also has_many :opportunities, through: :interests

    – MrYoshiji
    Mar 8 at 17:47


















  • Exact. It seems to work. I have just an undefined method 'fetch' for string which just appeared when clicked but it generated the good numbers of buttons.

    – Maceoz
    Mar 8 at 16:47











  • @Maceoz I updated my answer with the fixed code. I was not expecting that ActionController::Parameters.new(a: 1).require(:a) would return the value, but a copy of the hash with only allowed/required key/value pairs

    – MrYoshiji
    Mar 8 at 17:02












  • Thank you ! I'm on the way, I can now see the opportunity_id in the parameters. An other error appeared but due to my nested associations (HasManyThroughNestedAssociations). Probably a problem on my models (has_many like suggested by Alan).

    – Maceoz
    Mar 8 at 17:22











  • @Maceoz yes, a User has_many :interests and therefore it also has_many :opportunities, through: :interests

    – MrYoshiji
    Mar 8 at 17:47

















Exact. It seems to work. I have just an undefined method 'fetch' for string which just appeared when clicked but it generated the good numbers of buttons.

– Maceoz
Mar 8 at 16:47





Exact. It seems to work. I have just an undefined method 'fetch' for string which just appeared when clicked but it generated the good numbers of buttons.

– Maceoz
Mar 8 at 16:47













@Maceoz I updated my answer with the fixed code. I was not expecting that ActionController::Parameters.new(a: 1).require(:a) would return the value, but a copy of the hash with only allowed/required key/value pairs

– MrYoshiji
Mar 8 at 17:02






@Maceoz I updated my answer with the fixed code. I was not expecting that ActionController::Parameters.new(a: 1).require(:a) would return the value, but a copy of the hash with only allowed/required key/value pairs

– MrYoshiji
Mar 8 at 17:02














Thank you ! I'm on the way, I can now see the opportunity_id in the parameters. An other error appeared but due to my nested associations (HasManyThroughNestedAssociations). Probably a problem on my models (has_many like suggested by Alan).

– Maceoz
Mar 8 at 17:22





Thank you ! I'm on the way, I can now see the opportunity_id in the parameters. An other error appeared but due to my nested associations (HasManyThroughNestedAssociations). Probably a problem on my models (has_many like suggested by Alan).

– Maceoz
Mar 8 at 17:22













@Maceoz yes, a User has_many :interests and therefore it also has_many :opportunities, through: :interests

– MrYoshiji
Mar 8 at 17:47






@Maceoz yes, a User has_many :interests and therefore it also has_many :opportunities, through: :interests

– MrYoshiji
Mar 8 at 17:47














-1














First, you need to pass the ids of the opportunities you want to create interest some way, the best is a form, with checkboxes like MrShemek said, or a multi select dropdown.



I think you probably made some mistakes in User and Opportunity with the has_many and belong_to part:



class User < ApplicationRecord
has_many :interests
has_many :opportunities, through: :interests
# interest is the one that links user and opportunity, it has the references for both user and opportunities
end
class Opportunity < ApplicationRecord
has_many :interests
has_many :users, through: :interests
end


then in controller you could do



def create
@user = current_user
@opportunities = Opportunity.all
@user.opportunity_ids = interest_params[:opportunity_ids] # it will create the interrests automatically for the given ids (because the relations of has_many through)
if @user.save!
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice:"it doesn't work"
end
end





share|improve this answer























  • the ids writers are dangerous. they have persistence effect: User.first.opportunity_ids = [] will actually trigger DELETE statements without even running validations or callbacks, and still do it even though you did not save the user object. Yep, that's crazy, I know... Don't use _ids generated methods on update (because it works properly on create)

    – MrYoshiji
    Mar 8 at 16:55
















-1














First, you need to pass the ids of the opportunities you want to create interest some way, the best is a form, with checkboxes like MrShemek said, or a multi select dropdown.



I think you probably made some mistakes in User and Opportunity with the has_many and belong_to part:



class User < ApplicationRecord
has_many :interests
has_many :opportunities, through: :interests
# interest is the one that links user and opportunity, it has the references for both user and opportunities
end
class Opportunity < ApplicationRecord
has_many :interests
has_many :users, through: :interests
end


then in controller you could do



def create
@user = current_user
@opportunities = Opportunity.all
@user.opportunity_ids = interest_params[:opportunity_ids] # it will create the interrests automatically for the given ids (because the relations of has_many through)
if @user.save!
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice:"it doesn't work"
end
end





share|improve this answer























  • the ids writers are dangerous. they have persistence effect: User.first.opportunity_ids = [] will actually trigger DELETE statements without even running validations or callbacks, and still do it even though you did not save the user object. Yep, that's crazy, I know... Don't use _ids generated methods on update (because it works properly on create)

    – MrYoshiji
    Mar 8 at 16:55














-1












-1








-1







First, you need to pass the ids of the opportunities you want to create interest some way, the best is a form, with checkboxes like MrShemek said, or a multi select dropdown.



I think you probably made some mistakes in User and Opportunity with the has_many and belong_to part:



class User < ApplicationRecord
has_many :interests
has_many :opportunities, through: :interests
# interest is the one that links user and opportunity, it has the references for both user and opportunities
end
class Opportunity < ApplicationRecord
has_many :interests
has_many :users, through: :interests
end


then in controller you could do



def create
@user = current_user
@opportunities = Opportunity.all
@user.opportunity_ids = interest_params[:opportunity_ids] # it will create the interrests automatically for the given ids (because the relations of has_many through)
if @user.save!
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice:"it doesn't work"
end
end





share|improve this answer













First, you need to pass the ids of the opportunities you want to create interest some way, the best is a form, with checkboxes like MrShemek said, or a multi select dropdown.



I think you probably made some mistakes in User and Opportunity with the has_many and belong_to part:



class User < ApplicationRecord
has_many :interests
has_many :opportunities, through: :interests
# interest is the one that links user and opportunity, it has the references for both user and opportunities
end
class Opportunity < ApplicationRecord
has_many :interests
has_many :users, through: :interests
end


then in controller you could do



def create
@user = current_user
@opportunities = Opportunity.all
@user.opportunity_ids = interest_params[:opportunity_ids] # it will create the interrests automatically for the given ids (because the relations of has_many through)
if @user.save!
redirect_to user_interests_path, notice: 'it works'
else
render :new, notice:"it doesn't work"
end
end






share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 8 at 16:48









Alan ThomazAlan Thomaz

1




1












  • the ids writers are dangerous. they have persistence effect: User.first.opportunity_ids = [] will actually trigger DELETE statements without even running validations or callbacks, and still do it even though you did not save the user object. Yep, that's crazy, I know... Don't use _ids generated methods on update (because it works properly on create)

    – MrYoshiji
    Mar 8 at 16:55


















  • the ids writers are dangerous. they have persistence effect: User.first.opportunity_ids = [] will actually trigger DELETE statements without even running validations or callbacks, and still do it even though you did not save the user object. Yep, that's crazy, I know... Don't use _ids generated methods on update (because it works properly on create)

    – MrYoshiji
    Mar 8 at 16:55

















the ids writers are dangerous. they have persistence effect: User.first.opportunity_ids = [] will actually trigger DELETE statements without even running validations or callbacks, and still do it even though you did not save the user object. Yep, that's crazy, I know... Don't use _ids generated methods on update (because it works properly on create)

– MrYoshiji
Mar 8 at 16:55






the ids writers are dangerous. they have persistence effect: User.first.opportunity_ids = [] will actually trigger DELETE statements without even running validations or callbacks, and still do it even though you did not save the user object. Yep, that's crazy, I know... Don't use _ids generated methods on update (because it works properly on create)

– MrYoshiji
Mar 8 at 16:55


















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55066998%2frails-how-to-create-multiple-matches-in-one-action-between-a-user-and-opport%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

Алба-Юлія

Захаров Федір Захарович